Vuex模組化
阿新 • • 發佈:2021-02-04
Vuex由於使用單一狀態樹,應用的所有狀態會集中到一個比較大的物件。當應用變得非常複雜時,store 物件就有可能變得相當臃腫。
因此,Vuex 允許我們將 store 分割成模組(module),每個模組擁有自己的 state、mutation、action、getter、甚至是巢狀子模組。
預設情況下,模組內部的 action、mutation 和 getter 是註冊在全域性名稱空間的,這樣使得多個模組能夠對同一 mutation 或 action 作出響應。如果希望你的模組具有更高的封裝度和複用性,此時就用到了名稱空間這個概念。
Vuex模組引入操作:
about.vue
<template>
<div class="about">
<h1 @click="setMallname('Green')">{{mall.mallname}}</h1>
<h1 @click="setLuntanname('Gluntan')">{{luntanname}}</h1>
</div>
</template>
<script>
import { mapState,mapGetters, mapActions, mapMutations } from 'vuex'
export default{
mounted(){
console.log(this);
//觸發vuex的action方法
// this.$store.dispatch('getJoke')
// this.getJoke()
},
methods:{
// addAge:function(){
// this.$store.commit('addAge', 3)
// }
...mapActions(['getJoke' ]),
...mapMutations(['addAge','getList','setMallname']),
...mapMutations('luntan',['setLuntanname']) //設定名稱空間後,引入方式有所不同。
},
computed:{
...mapState(['mall']), //結構mapState
...mapState('luntan',['luntanname'])
}
}
</script>
設定名稱空間後,引入方式有所不同。…mapMutations(‘luntan’,[‘setLuntanname’]) 先匯入luntan名稱,然後設定引入屬性
luntan.js
export default {
namespaced:true,
state : {
luntanname:"格林lt"
},
mutations:{
setLuntanname:function(state,payload){
state.luntanname = payload
}
}
}
index.js
import luntan from './luntan'
modules: {
luntan
}