為什么要分模塊:
由於使用單一狀態樹,應用的所有狀態會集中到一個比較大的對象。當應用變得非常復雜時,store 對象就有可能變得相當臃腫。為了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter(模塊大的話可以把 state、mutation、action、getter拆分成獨立的文件)。
案例
src/store/card/index.js (子模塊)
方式一:state、mutation、action、getter統一寫在index.js
const card = {
/**
* 定義命名空間,防止多個模塊同名共享,使用時需要帶上命名空間
*/
namespaced: true,
state: {
cardArr: [],
},
mutations: {
addCard(state, obj){
state.cardArr.push(obj);
}
},
actions: {
addCardFun(store, obj){
store.commit('addCard', obj);
}
}
}
//導出
export default card;
方式二:state、mutation、action、getter拆分成獨立的文件
src/store/card/state.js
export default {
cardArr: []
}
src/store/card/mutations.js
export default {
addCard(state, obj){
state.cardArr.push(obj);
}
}
src/store/card/actions.js
export default {
addCardFun(store, obj){
store.commit('addCard', obj);
}
}
src/store/card/index.js (子模塊)
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
src/store/index.js(在總的store中中配置vuex)
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import card from './card'
//構造store
const store = new Vuex.Store({
// 模塊化
modules: {
card: card
}
});
export default store;
在card.vue中使用store里的數據
<template>
<div>
顯示卡列表:<button @click="onAdd">追加卡信息</button>
<ul>
<li v-for="(result, index) in cardArr" :key="index">
卡號:{{result.no}} <br>
昵稱:{{result.name}}
</li>
</ul>
</div>
</template>
<script>
// 導入state、mapMutations、actions
import { mapState, mapMutations, actions } from 'vuex';
export default {
data(){
return {
}
},
computed:{
// 映射帶有命名空間的state,第一個參數模塊名
...mapState('card', [
cardArr: state => state.cardArr
])
},
methods: {
// 映射帶有命名空間的mutations,第一個參數模塊名
...mapMutations('card' ,[
'addCard',
]),
// 映射帶有命名空間的actions,第一個參數模塊名
...mapActions('card', [
'addCardFun'
])
onAdd(){
...
//this.$store.commit('card/addCard', data);
this.addCard(data);
// 通過actions調用
//this.$store.dispatch('card/addCardFun', data)
this.addCardFun(data);
}
}
}
</script>