Vue 引入 TypeScript
Vue 在 官方文档中有一节简单的介绍了如何引入 TypeScript,可惜文档太过简单,真正投入生产还有许多的细节没有介绍。
我们对此进行了一系列探索,最后我们的风格是这样的:
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import { State, Action, Mutation, namespace } from 'vuex-class'
import Toast from 'components/Toast.vue'
const userState = namespace('business/user', State)
@Component({
components: { Toast },
})
export default class extends Vue {
// data
title = 'demo'
@Prop({ default: '' })
text: string
// store
@userState userId
// computed
get name (): boolean {
return this.title + this.text
}
// watch
@Watch('text')
onChangeText () { }
// hooks
mounted() { }
}
大体来说,Vue 引入 TypeScript 可以用到这些生态库:
-
vue-class-component:强化 Vue 组件,使用 TypeScript/装饰器 增强 Vue 组件
-
vue-property-decorator:在 vue-class-component 上增强更多的结合 Vue 特性的装饰器
-
vuex-class:在 vue-class-component 提供 Vuex 的绑定 vuex-ts-decorators:让Vuex 和 TypeScript 结合