【发布时间】:2018-05-18 16:11:45
【问题描述】:
我有这个 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 flag 并且可以像这样使用这个模块:
this.$store.state.things.firstThing // <-- return abc here
this.$store.commit('things/setFirstThing', 10)
this.$store.getters['things/getFirstThing'] // <-- return abc here
如果我将使用像 Vuex 中的 official example 这样的常量,并像这样重构我的 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/ 来声明突变/动作/getters:
const getters = {
['things/' + Types.getters.GET_FIRST_THING]: state => state.firstThing,
['things/' + Types.getters.GET_SECOND_THING]: state => state.secondThing,
};
如何避免?
【问题讨论】:
标签: javascript vue.js vuejs2 vuex