面試官:說說如何在Vue項目中應用TypeScript?
一、前言
與如何在React項目中應用TypeScript類似
在VUE項目中應用typescript,我們需要引入一個庫vue-property-decorator,
其是基于vue-class-component庫而來,這個庫vue官方推出的一個支持使用class方式來開發vue單文件組件的庫
主要的功能如下:
- methods 可以直接聲明為類的成員方法
- 計算屬性可以被聲明為類的屬性訪問器
- 初始化的 data 可以被聲明為類屬性
- data、render 以及所有的 Vue 生命周期鉤子可以直接作為類的成員方法
- 所有其他屬性,需要放在裝飾器中
二、使用
vue-property-decorator 主要提供了以下裝飾器
- @Prop
- @PropSync
- @Model
- @Watch
- @Provide
- @Inject
- @ProvideReactive
- @InjectReactive
- @Emit
- @Ref
- @Component (由 vue-class-component 提供)
- Mixins (由 vue-class-component 提供)
@Component
Component裝飾器它注明了此類為一個Vue組件,因此即使沒有設置選項也不能省略
如果需要定義比如 name、components、filters、directives以及自定義屬性,就可以在Component裝飾器中定義,如下:
- import {Component,Vue} from 'vue-property-decorator';
- import {componentA,componentB} from '@/components';
- @Component({
- components:{
- componentA,
- componentB,
- },
- directives: {
- focus: {
- // 指令的定義
- inserted: function (el) {
- el.focus()
- }
- }
- }
- })
- export default class YourCompoent extends Vue{
- }
computed、data、methods
這里取消了組件的data和methods屬性,以往data返回對象中的屬性、methods中的方法需要直接定義在Class中,當做類的屬性和方法
- @Component
- export default class HelloDecorator extends Vue {
- count: number = 123 // 類屬性相當于以前的 data
- add(): number { // 類方法就是以前的方法
- this.count + 1
- }
- // 獲取計算屬性
- get total(): number {
- return this.count + 1
- }
- // 設置計算屬性
- set total(param:number): void {
- this.count = param
- }
- }
@props
組件接收屬性的裝飾器,如下使用:
- import {Component,Vue,Prop} from vue-property-decorator;
- @Component
- export default class YourComponent extends Vue {
- @Prop(String)
- propA:string;
- @Prop([String,Number])
- propB:string|number;
- @Prop({
- type: String, // type: [String , Number]
- default: 'default value', // 一般為String或Number
- //如果是對象或數組的話。默認值從一個工廠函數中返回
- // defatult: () => {
- // return ['a','b']
- // }
- required: true,
- validator: (value) => {
- return [
- 'InProcess',
- 'Settled'
- ].indexOf(value) !== -1
- }
- })
- propC:string;
- }
@watch
實際就是Vue中的監聽器,如下:
- import { Vue, Component, Watch } from 'vue-property-decorator'
- @Component
- export default class YourComponent extends Vue {
- @Watch('child')
- onChildChanged(val: string, oldVal: string) {}
- @Watch('person', { immediate: true, deep: true })
- onPersonChanged1(val: Person, oldVal: Person) {}
- @Watch('person')
- onPersonChanged2(val: Person, oldVal: Person) {}
- }
@emit
vue-property-decorator 提供的 @Emit 裝飾器就是代替Vue中的事件的觸發$emit,如下:
- import {Vue, Component, Emit} from 'vue-property-decorator';
- @Component({})
- export default class Some extends Vue{
- mounted(){
- this.$on('emit-todo', function(n) {
- console.log(n)
- })
- this.emitTodo('world');
- }
- @Emit()
- emitTodo(n: string){
- console.log('hello');
- }
- }
三 、總結
可以看到上述typescript版本的vue class的語法與平時javascript版本使用起來還是有很大的不同,多處用到class與裝飾器,但實際上本質是一致的,只有不斷編寫才會得心應手