在vuex中提交 mutation 是更改状态的唯一方法,并且这个过程是同步的,异步逻辑都应该封装到 action 里面。对于mutation/action,有一个常见的操作就是传参,也就是官网上说的“提交载荷”。
mutation传参
朴实无华的方式
mutation.js
//vuex中的mutation const mutations = { increment: (state,n) => { //n是从组件中传来的参数 state.count += n; } } export default mutations;
vue组件中(省去其他代码)
methods: { add(){ //传参 this.$store.commit('increment',5); } }
对象风格提交参数
mutation.js
//vuex中的mutation const mutations = { decrementa: (state,payload) => { state.count -= payload.amount; } } export default mutations;
vue组件
methods: { reducea(){ //对象风格传参 this.$store.commit({ type: 'decrementa', amount: 5 }); }, }
action传参
朴实无华
action.js
/vuex中的action const actions = { increment(context,args){ context.commit('increment',args); } } export default actions;
mutation.js
//vuex中的mutation const mutations = { increment: (state,n) => { state.count += n; } } export default mutations;
vue组件
methods: { adda(){ //触发action this.$store.dispatch('increment',5); } }
对象风格
action.js
//vuex中的action const actions = { decrementa(context,payload){ context.commit('decrementa',payload); } } export default actions;
mutation.js
//vuex中的mutation const mutations = { decrementa: (state,payload) => { state.count -= payload.amount; } } export default mutations;
vue组件
methods: { reduceb(){ this.$store.dispatch({ type: 'decrementa', amount: 5 }); } }