vuex 進階教學:Module、Getter
文章推薦指數: 80 %
接續上回〈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]
訂閱:
延伸文章資訊
- 1Mocking a getter in Vuex + Jest | Toucan Toco
You don't want to use the “real” getter, because that would not be a unit test ... Pizza.vue'; co...
- 2那些關於Vue 的小細節- Computed 中getter 和setter 觸發的 ...
另外,在getter 中,要記得搭配使用return 來把值返回出來。 基本的寫法如下:. 預設只有getter 的computed. new Vue({ ...
- 3How to set up Pinia getter in Vue 3 Composition API - Stack ...
- 4Getter | Vuex
Vuex 允许我们在store 中定义“getter”(可以认为是store 的计算属性)。 注意. 从Vue 3.0 开始,getter 的结果不再像计算属性一样会被缓存起来。这是一个 ...
- 5[Vue] Vuex 是什麼? 怎麼用? — Getters (3/5) | by itsems - Medium
在沒有getters 的時候,我們需要在template 處理抓回來的state ,才能達到這件事情,先在store.js 裡面加上一個mutations 把api 抓回來的值丟進state ...