重學Vue(五)--typescript

前言

在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。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章