action 不能直接变更状态,而是用于提交mutation
mutation只能进行同步操作,而action可进行异步操作.
action接收一个与store实例具有相同属性和方法的context对象作为参数,所以可通过context.commit(‘typeName’)进行提交mutation,也可以通过context.state以及context.getters获取state和getters.但是context并不是store实例本身.
action通过 store.dispatch 触发
const store = new Vuex.Store({
state: {
count: 0
},
mutations: { //定义mutation
increment (state) {
state.count++
}
},
actions: {
incrementAsync ({ commit }) { //其中可进行异步操作
setTimeout(() => {
commit('increment') //提交mutation
}, 1000)
}
}
})
store.dispatch('increment') //触发action
action支持与mutation同样的载荷方式和对象方式进行分发
你在组件中使用 this.$store.dispatch(‘xxx’) 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}
一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。
组合action( 暂时不太懂 ???? )
actions: {
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
利用 async / await 这个 JavaScript 即将到来的新特性,我们可以像这样组合 action:
// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}