Module 模塊
前言:
如果你項(xiàng)目非常大,如果只有一個(gè)模塊來(lái)維護(hù)數(shù)據(jù),那么這個(gè)模塊會(huì)非常大,
對(duì)于可維護(hù)性來(lái)說(shuō)就不是特別高,所以vuex給我們提供了模塊的功能
我們可以通過(guò)modules來(lái)將vuex處理為多個(gè)模塊
1. 定義Store中的模塊
說(shuō)明:
- 通過(guò)store中的modules選項(xiàng)定義模塊
- 每個(gè)模塊都有自己的state,getter,mutation,action
示例代碼:
let moduleFruits = {
state:{
fruits:[{
name:"蘋(píng)果",
price: 22
},{
name:"梨子",
price: 25
},{
name:"西瓜",
price: 16
},{
name:"香蕉",
price: 18
}]
},
getters:{
filterFruits(state){
return state.fruits.filter(fruit => fruit.price > 20)
}
},
mutations:{
addFruit(state,payload){
console.log(arguments);
state.fruits.push({
name:payload.name,
price: payload.price
})
}
},
actions:{
asyncAdd(context,payload){
console.log(arguments);
context.commit("addFruit",payload)
}
}
}
let store = new Vuex.Store({
state:{
count:0,
user:{
name:"張三",
age:20
},
},
getters:{
//...
},
mutations:{
//...
},
actions:{
//...
},
modules:{
goods:moduleFruits
}
})
2. 組件中獲取模塊中的數(shù)據(jù)
2.1 獲取模塊中的state狀態(tài)
$store.state.goods.fruits
說(shuō)明:
-
$store
就是Store倉(cāng)庫(kù) -
state
獲取state
數(shù)據(jù) -
goods
為modules中的模塊名稱(chēng) -
fruits
為模塊goods
中state
數(shù)據(jù)
2.2 獲取getter計(jì)算屬性
$store.getters.filterFruits
注意:
- store中g(shù)etters的計(jì)算屬性不能和模塊中的getters計(jì)算屬性重名
- 如果重名,
vuex
用用store
中的getter
計(jì)算屬性替換模塊中的計(jì)算屬性
3. 組件操作store中的mutation和action
3.4 commit方法
觸發(fā)mutation中的方法和觸發(fā)store中的方法一直
this.$store.commit({
type:"increment",
name:"菠蘿",
price: 22
})
3.5 store中的mutation方法和store中的重名
說(shuō)明:
如果mutation方法重名,會(huì)先執(zhí)行store中的,在執(zhí)行自己
也就是說(shuō)所有同名的mutation函數(shù)都會(huì)執(zhí)行
只不過(guò)每一個(gè)mutation函數(shù)修改的狀態(tài)不同
3.6 dispatch方法
組件中使用dispath方法觸發(fā)action方法,
this.$store.dispath({
type:"asyncIncrement",
name:"菠蘿",
price: 22
})