分享一個vuex的小知識:
使用vuex,修改狀態用commit,或者dispatch,如
this.$store.commit('user/age', 10)
this.$store.dispatch('user/age', 10)
也可以使用mapActions和mapMutations進行映射,
使用方法:
...mapActions({
stateChange: 'user/updateUserinfo', // 對應store中模塊對應的actions方法名,
}),
將 this.stateChange()
映射爲 this.$store.commit('user/updateUserinfo')
...mapMutations({
stateChange: 'user/SET_USERINFO', // 對應store中mutations中的type名
}),
將 this.stateChange()
映射爲 this.$store.commit('user/updateUserinfo')
注意:
1:如果有參數傳遞,直接在綁定的元素上
stateChange(10)
,
或者如stateChange({name: '張三', age: 18})
將需要更新的數據組裝好再提交,
假如你在stateChange方法中先將參數進行處理,在組裝是不能實現state更新的,
mapActions和mapMutations無法進行異步更新;
2:vuex的模塊中namespaced爲true時,mapMutations和mapActions都需要加上完整的模塊名