我有一个 Vue 组件,它有一个使用装饰器定义的属性:
import { Component, Vue } from "vue-property-decorator"
@Component({
props: {
myId: String,
},
})
class TestProp extends Vue {
myFunction(obj: any) {
return obj[this.myId] // here tslint complains: "Property 'myId' does not exist on type 'TestProp'."
}
}
我可以通过将this
转换为any
来避免类型错误:
myFunction(obj: any) {
return obj[(this as any).myId]
}
但这与其说是解决方案,不如说是一种解决方法。
我想编译器不知道@Component
装饰器定义的属性?
有什么想法吗?
我建议你使用这个库:https://github.com/kaorun343/vue-property-decorator
有了这个,你可以在组件类中声明你的 prop。
例如:
import { Vue, Component, Prop } from 'vue-property-decorator'
@Component
class TestProp extends Vue {
@Prop(String) myId: string!
}
TypeScript 示例指出,您必须在组件中自行记录它们。
从该页面
// additional declaration is needed
// when you declare some properties in `Component` decorator
import { Component, Vue } from "vue-property-decorator"
@Component({
props: {
myId: String,
},
})
class TestProp extends Vue {
myId: string;
myFunction(obj: any) {
return obj[this.myId] // here tslint complains: "Property 'myId' does not exist on type 'TestProp'."
}
}