我们可以先了解一下在 Vue
中使用 Typescript
非常好用的几个库:
vue-class-component
:vue-class-component
是一个Class Decorator
,也就是类的装饰器vue-property-decorator
:vue-property-decorator
是基于 vue 组织里vue-class-component
所做的拓展
import { Vue, Component, Inject, Provide, Prop, Model, Watch, Emit, Mixins } from 'vue-property-decorator'
vuex-module-decorators
: 用Typescript
写 vuex 很好用的一个库
import { Module, VuexModule, Mutation, Action, MutationAction, getModule } from 'vuex-module-decorators'
vue-property-decorators
仓库GitHub地址:https://github.com/kaorun343/vue-property-decorator
Vue中使用TypeScript时,用到了一个非常好用的库:vue-property-decorators
,
它使用装饰器来简化书写, 这个组件完全依赖于vue-class-component
它具备以下几个属性:
@Component
(完全继承于vue-class-component)@Emit
@Inject
@Provice
@Prop
@Watch
@Model
Mixins
(在vue-class-component中定义);
安装
npm i -s vue-property-decorator
使用
当我们在vue单文件中使用TypeScript
时,引入vue-property-decorator
之后,script中的标签就变为这样:
<script lang="ts">
import { Component, Prop, Vue, Ref } from 'vue-property-decorator';
// import { State, Action, namespace } from 'vuex-class';
@Component({})
export default class "组件名" extends Vue{
loading: boolean = false;
ValB: number = 1;
formData: any = {};
}
</script>
等同于
<script lang="es6">
import Vue from 'vue';
export default {
data(){
return {
loading: false,
ValB: 1,
formData:{}
}
}
}
</script>
总结: 对于data
里的变量,可以直接按ts定义类变量的写法写,如果是计算属性,就要用到getter了.
<script lang="ts">
import {Vue, Component} from 'vue-property-decorator';
@Component({})
export default class "组件名" extends Vue{
get isMiniVideo() {
return this.type === 'miniVideo';
}
}
</script>
Vue中的计算属性,我们只需要将该计算属性名定义为一个函数,并在函数前加上get关键字即可.
原本Vue中的computed里的每个计算属性都变成了在前缀添加get的函数.
@Component
@Component
装饰器可以接收一个对象作为参数,可以在对象中声明 components
,filters
,directives
等未提供装饰器的选项,也可以声明computed
,watch
等
import BaseTable from '@/components/BaseTable.vue';
import DialogBox from '@/components/DialogBox.vue';
@Component({
components: {
BaseTable,
DialogBox,
},// 注入组件
filters: {
toFixed: (num: number, fix: number = 2) => {
return num.toFixed(fix)
}
}, // 声明filters
})
export default class CpIncomeAllocation extends Vue {
}