分发 Action
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
分发 Action
Action 通过 store.dispatch 方法触发:
乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation必须同步执行这个限制么?Action就不受约束! 我们可以在 action 内部执行异步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}Actions 支持同样的载荷方式和对象方式进行分发:
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
mapActions
同样地,action也有相对应的mapActions 辅助函数
mapActions
mapActions 辅助函数跟mapMutations一样都是组件的 methods 调用:
import { mapActions } from 'vuex'export default {
// ...
methods: {
...mapActions([
'increment' // 映射 this.increment() 为 this.$store.dispatch('increment')
]),
...mapActions({
add: 'increment' // 映射 this.add() 为 this.$store.dispatch('increment')
})
}
}
mutation-types
关于mutation-types方面的讲解官方文档很少说明,但在实际的中大项目中,对==mutation-types==的配置是必不可少的,Vuex的文档只讲解了state,getters,mutation,actions四个核心概念,下面我简单补充下mutation-types的使用。
顾名思义,==mutation-types==其实就是mutation实例中各个方法的设定,一般要mutation方法前先在mutation-types用大写写法设定,再在mutation里引入使用,下面看看项目实际使用:
项目组织结构

在mutation-types定义好mutation的方法结构:
//SET_SINGER,SET_SONG 为mutation中要使用的方法名export const SET_SINGER = 'SET_SINGER'
export const SET_SONG = 'SET_SONG'
在mutation中导入使用:
import * as types from ',/mutation-types.js'const mutations = {
[types.SET_SINGER](state, singer) {
....
},
[types.SET_SONG](state, song) {
....
}
}
结语
看完上面对vuex的讲解相信你已经入门了,现在可以看看具体的项目加深理解,可以参考我的github一个购物车例子: https://github.com/osjj/vue-shopCart










