【问题标题】:Vuex Namespaced Store Sets Both StatesVuex 命名空间存储设置两种状态
【发布时间】:2021-12-05 17:42:07
【问题描述】:

在我的项目中,我有一个相当复杂的 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,
      },
    });

我的模块看起来像这样:

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,
};

问题是,如果我像这样对这些命名空间中的任何一个进行更改:

this.$store.commit('filter1/' + SET_ID_FILTER, '123');

这两个功能:

this.$store.state['filter1'].idFilter
this.$store.state['filter2'].idFilter

返回相同的。即使我什至没有设置。 filter2 上的 idFilter。

我是否使用了错误的命名空间?

【问题讨论】:

    标签: vue.js namespaces vuex store


    【解决方案1】:

    问题是两个模块副本中的状态是同一个对象。如果一个模块应该被重用,则应该使用工厂函数创建初始状态:

    const state = () => ({
      idFilter: null,
    });
    ...
    export default {
      namespaced: true,
      state,
      ...
    };
    

    这就是state被允许作为一个函数的原因。

    【讨论】:

      猜你喜欢
      • 2020-11-24
      • 2021-03-16
      • 2019-03-22
      • 2018-11-04
      • 2020-06-08
      • 2019-07-02
      • 2018-10-29
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多