此外,这里有个 PR 暴露一个更直观的类型( Vue 2.6 版本才可以用):
props: {
testProp: Object as PropTypes<{ test: boolean }>
}
复制代码
vue-class-component
得益于 vue-propperty-decorator Prop 修饰器,当给 Prop 增加类型推断时,这些将变得简单:
import { Component, Vue, Prop } from 'vue-property-decorator'
@Component
export default class Test extends Vue {
@Prop({ type: Object })
private test: { value: string }
}
复制代码
当我们在组件内访问 test
时,便能获取它正确的类型信息。
mixins
mixins 是一种分发 Vue 组件中可复用功能的一种方式。当在 TypeScript 中使用它时,我们希望得到有关于 mixins 的类型信息。
当你使用 Vue.extends()
时,这有点困难,它并不能推断出 mixins 里的类型:
// ExampleMixin.vue
export default Vue.extend({
data () {
return {
testValue: 'test'
}
}
})
// other.vue
export default Vue.extend({
mixins: [ExampleMixin],
created () {
this.testValue // error, testValue 不存在!
}
})
复制代码
我们需要稍作修改:
// other.vue
export default ExampleMixin.extend({
mixins: [ExampleMixin],
created () {
this.testValue // 编译通过
}
})
复制代码
但这会存在一个问题,当使用多个 mixins 且推断出类型时,这将无法工作。而在这个 Issuse 中官方也明确表示,这无法被修改。
使用 vue-class-component 这会方便很多:
// ExampleMixin.vue
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export class ExampleMixin extends Vue {
public testValue = 'test'
}
// other.vue
import Component, { mixins } from 'vue-class-component'
import ExampleMixin from 'ExampleMixin.vue'
@Component({
components: {
ExampleMixin
}
})
export class MyComp extends mixins(ExampleMixin) {
created () {
console.log(this.testValue) // 编译通过
}
}
复制代码
也支持可以传入多个 mixins。
一些其它
做为 Vue 中最正统的方法(与标准形式最为接近),Vue.extends()
有着自己的优势,在 VScode Vetur 插件辅助下,它能正确提示子组件上的 Props: