發表文章

目前顯示的是有「vuex」標籤的文章

Vue那些我踩過的坑(Vuex-TypeScript)

圖片
在var來var去的同時雖然很方便,但也留下了許多技術債,在專案變大的同時未來是需要還的,但是在Vuex裡面使用TypeScript是非常痛苦的,因為VUEX本身的寫法是不支援TypeScript,這邊我示範一下如何重新定義store能夠好好低與typeScript結合吧 Store結構: type,是定義本身型別放置的地方 store │ index.ts │ type.ts │ └───rootComic actions.ts getters.ts index.ts mutation.ts type.ts index.d.ts: 我們可以從index底層Store的code,看到有個模板可以轉換成你想要的物件,裡面的 <S> 就是你定義的型別 export interface StoreOptions<S> { state?: S | (() => S); getters?: GetterTree<S, S>; actions?: ActionTree<S, S>; mutations?: MutationTree<S>; modules?: ModuleTree<S>; plugins?: Plugin<S>[]; strict?: boolean; devtools?: boolean; } Store定義: Step1: 開一個type.ts的檔案宣告我們 <S> 的型別,State本是個放資料的地方,要放資料的地方一定少不了interface,我們就以interface的方式來定義我們的state吧 export interface RootState { "rootmessage": string } Step2: 原本的寫法 import { createStore } from 'vuex' export default createStore({ state: { }, mutations: { }, actions: { }, modules: { } });