H女王范儿 2019-09-08
注意看注释 关键属性modules
state
getters
mutations
actions
const store = new Vuex.Store({ modules: { someModaule1: { // 模块1 namespaced: true, state: { // 状态 count: 0 }, getters: { // getters,会缓存属性 getCount: (state, getters) => { return state.someMOdaule1.count + getters.length } }, actions: { // 动作 ,支持异步,结果还是要触发 Mutation, 通过 store.dispatch('someModaule1/increment')触发 increment (context,arg) { console.log(arg) context.commit('increment') } }, mutations: { // Mutation必须为同步函数,去改变state, store.commit('someMOdaule1/increment', 10) increment (state, n) { state.count += n } }, modules: { // 嵌套模块 someModaule1: { // 继承父模块的命名空间 state: { ... }, getters: { profile () { ... } // -> getters['someModaule1/someModaule1'] } }, } }, someModauleOther: {...} // 其他模块 } })
调用
store.dispatch('someModaule1/increment') // 触发action store.commit('someMOdaule1/increment', 10) // 触发mutations
大型项目通常用如下方法mapState()
mapGetters()
mapActions()
mapMutations()
Vue.use(Vuex) const Counter = { template: `<div>{{ count }}</div>`, store:store, // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件 computed: { computed: { ...mapState('someModaule1', { 'count', // 传字符串参数 'count' 等同于 `state => state.count` 映射 this.count 为 store.someModaule1.state.count }), ...mapGetters('someModaule1',[ 'getCount', ]) }, }, methods: { ...mapActions('someModaule1',[ 'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('someModaule1/increment')` ]), ...mapMutations([ 'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')` ]) } }
mapState和其他map快捷方法接受的类型挺多要注意