使用 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 集成的時候,成本更低。


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

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


相關文章:
【推薦】 什么是高防服務器?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM