mapMutations是vuex的mutation的輔助函數,用於在組件中映射mutation內的方法,以便在該組件中直接使用mutation里的方法 (說白了,就是一語法糖)
1.在組件中導入vuex中的mapMutations:
import { mapMutations } from 'vuex'
2.在組件中導入mutation里的方法名:
...mapMutations([ //使用es6的拓展運算符
'INCREASE_SHOPCART',
'DECREASE_SHOPCART'
])
//約定將mutation里的方法名為大寫,並且導入時要給其加上引號
這一步,是將mutation里的函數映射到組件里,在組件里 :
this.INCREASE_SHOPCART === this.$store.commit('INCREASE_SHOPCART') //true
在有參數的情況下,mutation的state默認參數可以省略 :
this.INCREASE_SHOPCART(id) === this.$store.commit('INCREASE_SHOPCART',id) //true
舉個栗子:點擊btn按鈕增減商品數量
- 組件dom :
//shopCart.vue
//template
<button class="fl" @click='decrease(item.id)'>-</button>
<input type="number" class="fl" v-model="item.count" >
<button class="fl" @click='increase(item.id)'>+</button>
- mutations :
//mutations.js
INCREASE_SHOPCART(state,id){
state.shopCartData.forEach(e=>{
if(e.id === id){
e.count ++
}
})
},
DECREASE_SHOPCART(state,id){
state.shopCartData.forEach(e=>{
if(e.id === id && e.count >1){
e.count --
}
})
}
- 組件里的methods:
import { mapMutations } from 'vuex' // 先從vuex里導入 mapMutations
methods:{
...mapMutations([
'INCREASE_SHOPCART', //將mutation里的方法映射到該組件內
'DECREASE_SHOPCART' //等同於this.$store.commit('DECREASE_SHOPCART')
]),
increase(id){
this.INCREASE_SHOPCART(id)
//由於上一步已經將mutation映射到組件內,所以組件可以直接調用INCREASE_SHOPCART
}
decrease(id){
this.DECREASE_SHOPCART(id)
//同理
}
}
以上。