【问题标题】:Separated Vuex for each Vue instance on the page为页面上的每个 Vue 实例分隔 Vuex
【发布时间】:2021-08-30 15:32:32
【问题描述】:

我正在页面上实例化多个 Vue 应用程序:

import Vue from "vue";
import App from "./App.vue";
import useStore from "./store";

const arr = [1, 2];
for (const index of arr) {
  const store = useStore();

  new Vue({
    router,
    store,
    render: (h) => h(App)
  }).$mount(`#app$_{index}`);
}

我的商店文件如下所示:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import address from "./modules/address";

export default function useStore() {
  return new Vuex.Store({
    modules: { address }
  });
}

及地址模块:

const state = {
  address: null
};

const getters = {
  address(state) {
    return state.address;
  }
};

const mutations = {
  setAddress(state, address) {
    state.address = address;
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations
};

但商店似乎在页面上的所有 Vue 实例之间共享。 为什么,当我为每个 Vue 应用程序创建一个新实例时?

谢谢

【问题讨论】:

  • 与 cookie 一样,浏览器通过主机 AFAIK。如果商店有共享字段,您可能必须为每个实例化的商店实现一个前缀。

标签: javascript vue.js vuejs2 vuex


【解决方案1】:

问题不在于 Vuex 存储在多个 Vue 实例之间共享,实际上是地址模块的状态在多个 Vuex 存储之间共享。

Vuex 文档解决了这个问题:https://vuex.vuejs.org/guide/modules.html#module-reuse

如果我们使用普通对象来声明模块的状态,那么该状态对象将通过引用共享,并在它发生变异时导致跨存储/模块状态污染。

只需将地址模块状态声明从普通对象定义更改为函数定义:

const state = () => ({
  address: null
});

你很高兴!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2020-06-14
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多