前言
在vue中使用typescript是有些缺憾的,首先Vue2的类型系统并没有为Typescript做兼容,因为最开始选择的就是flow而不是TS,因此在Vue2中使用TS需要vue-property-decorator的帮助,从名字也看得出来,这里我们需要大量借助装饰器。
基本使用
基于TS的Vue开发是需要vue-property-decorator的辅助的,因此编程方式与JS的开发也有很大的区别。
首先是组件注册,不需要写在组件内部,直接写在class外边即可。
@Component({
components:{
componentA,
componentB,
},
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
})
其次是data和methods,也不需要在data和methods里面写,data就直接写成类属性,methods直接写成类方法。一般写成私有方法。
count: number = 123
add(): number {
this.count + 1
}
接着是Props,需要用装饰器:
@Prop(String)
propA:string;
@Prop([String,Number])
propB:string|number;
然后是computed,使用get set的写法:
private get nameComputed() {
const todo = _.find(this.getCurrentTodoList, this.id);
return todo!.name;
}
private set nameComputed(name) {
this.changeName({ id: this.id, value: name });
}
最后是Watch,使用装饰器加私有方法结合的方式。
@Watch("activeColor")
private changeColor(val: string, old: string) {
this.styleObj.background = val;
}
Vuex
配合Vuex使用的话,要使用vuex-class。
如State,定义好接口等基本的就不说了,mutation的类型去找Vuex的MutationTree<State>。
使用时需要引入
import { State, Mutation } from "vuex-class";
使用装饰器:
@State private todoItem!: ITodoItem[];
@Mutation
private selectColor!: (payload: { id: string; color: string }) => void;
最后还有Getter,作为store的计算属性,也是使用装饰器来完成:
export const getters = {
getCurrentTodoList(state: State): TodoItem[] {
return state.todoList;
},
};
@Getter
private getCurrentTodoList!: TodoItem[];
action暂缺。
VCA中的TS写法
Vue composition API是Vue3.0最重要的更新之一,其函数式编程思想其实和React Hooks如出一辙,只不过一个是不可变数据,一个是响应式;一个旨在淡化生命周期,一个继续沿用。
一些给出的TS工程的例子也是把组件写成了TSX,因为setup函数是支持返回一个JSX的,这一点仁者见仁,但是作为一个从React转来的开发者还是很亲切的。
首先是引入:
import { createComponent, PropType } from '@vue/composition-api';
至少不需要装饰器了,把组件用createComponent包裹一下即可:
export default createComponent({})
Props的:
props: {
msg: {
type: String,
required: true,
},
eventClick: {
type: (null as unknown) as PropType<(event: MouseEvent) => void>,
}
}
剩下的下一篇在讲,也是最后一篇了,做个Demo体验一下VCA。