Action asynchronous operation
Normal processing asynchronous operations, through a distribution store.dispatch action, commit changes state inside mutation action
- receiving an action having the same function and properties of the method and store context object instance.
- Submit mutation can call context.commit
- Obtaining state and getters by context.state and context.getters
The definition of Action
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++;
}
},
actions: {
increment (content) {
content.commit('increment')
}
}
});
Use dispatch distribution action
// 普通方式
this.$store.dispatch('increment');
// 派发并传参
this.$store.dispatch('increment', 100);
// 以对象的形式分发
this.$store.dispatch({
type: 'increment',
num: 100
});
mapAction Helper
import { mapAction } from 'vuex'
export default {
methods: {
// 以数组的形式
...mapActions([
// 将 this.increment() 映射为 this.$store.dispatch('increment')
'increment',
// 将 this.incrementBy(num) 映射为 this.$store.dispatch('incrementBy')
'incrementBy'
]),
...mapActions({
// 将 this.add() 映射为 this.$store.dispatch('increment')
add: 'increment'
})
}
}
Combined action
// 返回 Promise, 方便成功后派发下一个action
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation');
resolve();
}, 1000);
});
},
// 派发另一个action
actionB ({ dispatch, commit}) {
return dispatch.('actionA').then(() => {
commit('someOtherMutation');
});
}
}
// 派发action 可以通过 .then 方法指导执行完成了
this.$store.dispatch('actionA').then(() => {
// 派发并处理完了
});