vuex 進階教學:Module、Getter

文章推薦指數: 80 %
投票人數:10人

接續上回〈vuex 教學:vue 的狀態管理工具〉教學後,這次要延伸筆記Module、Getter 的使用,也包含較進階的用法,如果已經學完上一版的教學, ... Togglenavigation Siddharam 關於 有話對我說 Facebook 自由工作者日常 離職週記 工程師日常 慢慢想 技術筆記 浪流基隆 都市霧雨 文/西打藍Siddharam 前言 接續上回〈vuex教學:vue的狀態管理工具〉教學後,這次要延伸筆記Module、Getter的使用,也包含較進階的用法,如果已經學完上一版的教學,其實就很夠用了。

那我們就開始吧。

vuex進階 Module模組化。

當你的狀態過多且複雜時,就可以考慮運用Module來做切割,讓每個Module擁有自己的state、mutation、action、getter,方法很簡單: //store/index.js //官網教學範例 ... ... constmoduleA={ state:{...}, mutations:{...}, actions:{...}, getters:{...} } constmoduleB={ state:{...}, mutations:{...}, actions:{...} } conststore=newVuex.Store({ modules:{ a:moduleA, b:moduleB } }) ... ... 你也可以用資料夾分層,會更好維護: store/index.js /module/header/index.js /mutation.js /action.js /getter.js /footer/index.js /mutation.js /action.js /getter.js store/index.js ... ... importVuefrom'vue' importVuexfrom'vuex' importheaderfrom'./modules/header' importfooterfrom'./modules/footer' Vue.use(Vuex) exportdefaultnewVuex.Store({ modules:{ header, footer }, state:{ }, mutations:{ } }) ... ... 在Module中加入了namespaced,Vuex會在Module的action、mutation、getter加上prefix。

store/module/header/index.js ... ... importactionsfrom'./actions' importmutationsfrom'./mutations' importgettersfrom'./getters' exportdefault{ namespaced:true, state:{ id:null, spec:{ length:0 } }, actions, mutations, getters } ... ... getter 再來是getter,他讓你可以先行處理函式,功能類似於computed,例如: //store/index.js ... ... conststore=newVuex.Store({ state:{ todos:[ {id:1,text:'...',done:true}, {id:2,text:'...',done:false} ] }, getters:{ doneTodos:state=>{ returnstate.todos.filter(todo=>todo.done) }, //你也可以引入其他getter使用 doneTodosCount:(state,getters)=>{ returngetters.doneTodos.length } } }) ... ... 當你要使用時: //component/layout.vue ... ... computed:{ doneTodosCount(){ returnthis.$store.getters.doneTodosCount } } ... ... 另外,也能透過mapGetters引入getter來使用: //component/layout.vue ... ... import{mapGetters}from'vuex' exportdefault{ //... computed:{ ...mapGetters([ 'doneTodos', 'doneTodosCount' //... ]) } } ... ... 之前的專案,也幾乎沒用過getter,通常是把它架好後,就放著閒置了。

但module會用到,因為當多人共同開發系統時,只要維護各自的module就好,才不會動到彼此的架構。

閱讀量次 ← 上一篇 新的一篇 → 聯絡與合作 有文字採訪、網站開發,或是諮詢需求,皆可以至最新製作的個人網站參考作品。

或是想分享心情、聊聊天、交朋友,可以來秘密通道找我唷。

Email:[email protected] 訂閱:



請為這篇文章評分?