【发布时间】:2020-09-25 22:42:00
【问题描述】:
我正在使用选项 api,当尝试访问计算属性中的 Vue 数据对象的属性时,我在类型检查中遇到错误。
Property 'quantity' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, { item: unknown; total: unknown; menuItemCategories: any; }, Readonly<Record<never, any>>>'
该属性确实存在,因为页面能够使用计算属性正确加载和显示渲染模板 - 只有类型检查器会抱怨。
组件代码(长度简化):
import Vue from "vue";
export default Vue.extend({
data() {
quantity: 1,
},
computed: {
total() {
return this.item.price * this.quantity;
}
},
});
编辑
我已经能够通过将data 属性用作对象来解决此问题。
这确实会产生一些问题,因为最佳实践是使用data 作为返回对象的函数。同样的问题也适用于asyncData。
进一步的试验和错误表明我能够通过methods 属性访问data 函数属性。但是,如果我使用来自 vuex 的 mapGetters 助手,它会引发与计算属性相同的类型错误。
methods 在计算属性内的 CombinedVueInstance 类型中也不可用。
tsconfig.json
// tsconfig.json
{
"compilerOptions": {
"target": "es2018",
"module": "esnext",
"moduleResolution": "node",
"lib": [
"esnext",
"esnext.asynciterable",
"dom"
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"baseUrl": "./src",
"paths": {
"~/*": [
"./*"
],
"@/*": [
"./*"
]
},
"types": [
"@types/node",
"@nuxt/types",
"@nuxtjs/axios"
]
},
"exclude": [
"node_modules"
]
}
vue-shim.d.ts
declare module "*.vue" {
import Vue from 'vue'
export default Vue
}
【问题讨论】:
-
数据应该是一个返回对象的函数
-
@LawrenceCherone 我知道 - 我已经声明了它是一种让类型检查正常工作的解决方法。不能解决问题。
-
@LawrenceCherone 我在下一句中说过 - 请仔细阅读。
-
@LawrenceCherone 我采纳了自己的建议,并使用箭头函数而不是基本的 data() 函数进行了测试。它解决了这个问题。感谢您的帮助,如果我表现得粗鲁,我们深表歉意。
-
我在stackoverflow.com/questions/56002310/… 上回答了这个问题。我希望它会有所帮助。
标签: typescript vue.js vue-component nuxt.js