1. 程式人生 > >使用 typescript ,提升 vue 專案的開發體驗(2)

使用 typescript ,提升 vue 專案的開發體驗(2)

此文已由作者張漢銳授權網易雲社群釋出。

歡迎訪問網易雲社群,瞭解更多網易技術產品運營經驗。


vuex-class

提供了和 vuex 相關的全部裝飾器,從而解決了上面 Vue.extend + vuex 的 「程式碼提示」「程式碼重構」兩個問題,然後再通過手動新增型別宣告,使得「型別檢查」的工作也能生效


全部裝飾器有:


  • @State

  • @Getter

  • @Action

  • @Mutation


還有一個輔助函式:


  • namesapce  (用得比較少)


具體用法也很明確,看例子:


import Vue from 'vue'import Component from 'vue-class-component'import {
  State,
  Getter,
  Action,
  Mutation,
  namespace
} from 'vuex-class'const ModuleGetter = namespace('path/to/module', Getter)

@Component
export class MyComp extends Vue {  // 宣告 state,getter, action, mutation等,並手動新增型別
  @State('foo') stateFoo: number 
  @State(state => state.bar) stateBar: string
  @Getter('foo') getterFoo: number  
  @Action('foo') actionFoo: () => void
  @Mutation('foo') mutationFoo: () => void
  @ModuleGetter('foo') moduleGetterFoo: number  // If the argument is omitted, use the property name
  // for each state/getter/action/mutation type
  @State foo
  @Getter bar
  @Action baz
  @Mutation qux

  created () {    this.stateFoo // -> store.state.foo
    this.stateBar // -> store.state.bar
    this.getterFoo // -> store.getters.foo
    this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })
    this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })
    this.moduleGetterFoo // -> store.getters['path/to/module/foo']
  }
}


vue-mixin


這個庫提供的裝飾器,專門用於處理 vue 使用 mixin 的情況。裝飾器如下:


  • @Mixin

  • @Mixins

  • @Component : 對 vue-class-component 的封裝。在結合 vue-class-component 的時候,請使用這個 component


按照文件的例子,看下面 gif


Alt pic


另外,也支援多個 mixin ,詳情檢視文件介紹 vue-mixin-decorator


小結

介紹到這裡,通過加入幾個裝飾器,已經能夠保證 vue + ts 有了最基礎的開發體驗了。

雖然程式碼形式上有很大的變化,實際上還是 vue 的模樣(穿了馬甲,23333)。


其他:外掛型別宣告, Store.state 型別宣告

外掛型別宣告

vue 文件在 typescript 那一節已經有介紹,這裡就不再介紹,看 gif 吧


Alt pic


Store.state

為了更好的開發體驗,在訪問 this.$store.state 的時候有程式碼提示和型別檢查。目前版本(3.0.1) vuex 的型別宣告還不允許這麼做,需要 hack 下才能實現。

具體的 hack 方式是,通過  tsconfig.json 遮蔽官方的 vuex.d.ts 檔案,拷貝一份到 typings/vuex.d.ts,然後對 vuex 的 Store 宣告成自己的型別。

// tsconfig.json
{
  ...
  "paths": {
    "vuex": ["typings/vuex.d.ts"], // 這裡
  }
  ...}


// typings/vuex.d.ts import { RootState } from '../src/store';

declare module "vue/types/options" {
  interface ComponentOptions<V extends Vue> {      // 這裡宣告成自己的型別就行
      store?: Store<RootState>;
  }
}

declare module "vue/types/vue" {
  interface Vue {
      $store: Store<RootState>;
  }
}


詳細的前因後果,參考 Write Stores in Typescript  的討論


總結

到這裡,基本上 vue + ts 的體驗就會非常的好了,能夠利用到「程式碼提示」「型別檢查」「程式碼重構」等非常便利的工具,程式碼質量會在一定程度上有提升。期望在 vue 未來的版本上,能夠對 ts 有更好的支援,使得在 vue 全家桶和 ts 整合的時候,成本更低。


免費體驗雲安全(易盾)內容安全、驗證碼等服務

更多網易技術、產品、運營經驗分享請點選


相關文章:
【推薦】 如何作缺陷分析