Vuex namespaced


Vuex namespaced

namespaced: 用于划分不同模块的状态

案例

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
// 注册Vuex插件
Vue.use(Vuex)

const CounterOptions = {
    namespaced: true,
    // 修改数据的动作
    actions: {
        INCRE_ODD(context, payload) {
            context.state.count % 2 !== 0 && context.dispatch('INCRE_ASYNC', payload)
        },
        INCRE_ASYNC(context, payload) {
            setTimeout(() => {
                context.commit('incre', payload)
            }, 500);
        },
        DECRE_ASYNC(context, payload) {
            setTimeout(() => {
                context.commit('decre', payload)
            }, 500);
        }
    },
    // 操作数据的行为
    mutations: {
        incre(state, payload) {
            state.count += payload
        },
        decre(state, payload) {
            state.count -= payload
        }
    },
    // 初始化数据
    state: {
        count: 0,
        prop1: 'prop1 value',
        prop2: 'prop2 value'
    },
    getters: {
        bigCount(state) {
            return state.count * 10
        }
    }
}

const PersonOptions = {
    namespaced: true,
    actions: {
        CHANGE_NAME(context, payload) {
            setTimeout(() => {
                context.commit('changeName', payload)
            }, 500);
        }
    },
    mutations: {
        changeName(state, payload) {
            state.name += payload
        }
    },
    state: {
        name: 'island'
    }
}

export default new Vuex.Store({
    modules: {
        CounterAbout: CounterOptions,
        PersonAbout: PersonOptions
    }
})

组件1 Counter.vue





组件2 Person.vue




vue