我有这个Vuex模块:
//modules/things.js
const state = {
firstThing: 'abc',
secondThing: 'def',
};
const getters = {
getFirstThing: state => state.firstThing,
getSecondThing: state => state.secondThing,
};
const mutations = {
setFirstThing: (state, payload) => state.firstThing = payload,
setSecondThing: (state, payload) => state.secondThing = payload
};
const actions = {};
export default {
namespaced: true, // <------
state,
mutations,
actions,
getters
};
我使用namespaced: true
标志,并且可以像下面这样使用该模块:
this.$store.state.things.firstThing // <-- return abc here
this.$store.commit('things/setFirstThing', 10)
this.$store.getters['things/getFirstThing'] // <-- return abc here
如果我将使用Vuex 官方示例中的常量,并modules/things.js
像这样重构我的文件:
export const Types = {
getters: {
GET_FIRST_THING: 'GET_FIRST_THING',
GET_SECOND_THING: 'GET_SECOND_THING',
},
mutations: {
SET_FIRST_THING: 'SET_FIRST_THING',
SET_SECOND_THING: 'SET_SECOND_THING',
}
};
const getters = {
[Types.getters.GET_FIRST_THING]: state => state.firstThing,
[Types.getters.GET_SECOND_THING]: state => state.secondThing,
};
const mutations = {
[Types.mutations.SET_FIRST_THING]: (state, payload) => state.firstThing = payload,
[Types.mutations.SET_SECOND_THING]: (state, payload) => state.secondThing = payload
};
我将不得不使用名称空间前缀:
this.$store.commit('things/' + Types.mutations.SET_FIRST_THING, 10);
this.$store.getters['things/' + + Types.getters.GET_FIRST_THING]
如果我将模块名称空间前缀包括在Types
常量中,则必须使用字符串前缀things/
进行突变/动作/获取器声明:
const getters = {
['things/' + Types.getters.GET_FIRST_THING]: state => state.firstThing,
['things/' + Types.getters.GET_SECOND_THING]: state => state.secondThing,
};
如何避免呢?