In my project I have a rather complex vuex store which saves values of filter inputs and converts them into filters I can use to later query the backend. I use those filters next to two different tables. If I filter for id = 123 in table1 I DO NOT want to have the filter in table2 to be id = 123. Thats why I created a module and try to use a namespaced store. My vuex store index.js looks something like this:
import myFilterModule from './filter.module';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
filter1: myFilterModule,
filter2: myFilterModule,
},
});
And my module looks like this:
const state = {
idFilter: null,
};
const actions = {};
const mutations = {
[SET_ID_FILTER](state, id) {
state.idFilter = id;
},
};
const getters = {
getFilter(state) {
return state.idFilter;
},
};
export default {
namespaced: true,
state: () => state,
actions,
mutations,
getters,
};
The problem is, if I commit a change on either of those namespaces like this:
this.$store.commit('filter1/' SET_ID_FILTER, '123');
Both of these functions:
this.$store.state['filter1'].idFilter
this.$store.state['filter2'].idFilter
Return the same. Even tho I didnt even set. idFilter on filter2.
Am I using the namespaces wrong?
CodePudding user response:
The problem is that a state is the same object in both module copies. If a module is supposed to be reused, initial state should be created with factory function:
const state = () => ({
idFilter: null,
});
...
export default {
namespaced: true,
state,
...
};
This is the reason why state
is allowed to be a function.