Tro*_*jan 2 namespaces store vue.js vuex
在我的项目中,我有一个相当复杂的 vuex 存储,它保存过滤器输入的值并将它们转换为我可以用来稍后查询后端的过滤器。我在两个不同的表旁边使用这些过滤器。如果我在 table1 中过滤 id = 123,我不希望 table2 中的过滤器为 id = 123。这就是我创建一个模块并尝试使用命名空间存储的原因。我的 vuex 商店 index.js 看起来像这样:
import myFilterModule from './filter.module';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
filter1: myFilterModule,
filter2: myFilterModule,
},
});
Run Code Online (Sandbox Code Playgroud)
我的模块如下所示:
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,
};
Run Code Online (Sandbox Code Playgroud)
问题是,如果我对这些命名空间中的任何一个进行更改,如下所示:
this.$store.commit('filter1/' + SET_ID_FILTER, '123');
Run Code Online (Sandbox Code Playgroud)
这两个函数:
this.$store.state['filter1'].idFilter
this.$store.state['filter2'].idFilter
Run Code Online (Sandbox Code Playgroud)
返回相同。即使我什至没有设置。过滤器 2 上的 idFilter。
我使用的命名空间错误吗?
问题是两个模块副本中的状态是相同的对象。如果要重用模块,则应使用工厂函数创建初始状态:
const state = () => ({
idFilter: null,
});
...
export default {
namespaced: true,
state,
...
};
Run Code Online (Sandbox Code Playgroud)
state这就是允许成为函数的原因。
| 归档时间: |
|
| 查看次数: |
1067 次 |
| 最近记录: |