0

I’m instantiating multiple Vue apps on the page:

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}`);
}

My store file looks like this:

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

And address module:

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

But the store seems to be shared across the all Vue instances on the page. Why, when I’m creating a new instance for each Vue app?

Thanks

1
  • As with cookies the browser goes by host AFAIK. If the stores have shared fields you might have to implement a prefix per store instantiated. Commented Aug 30, 2021 at 15:54

1 Answer 1

3

The problem isn't Vuex store being shared across multiple Vue instances, it is actually the Address module's state getting shared across multiple Vuex stores.

Vuex docs address this issue: https://vuex.vuejs.org/guide/modules.html#module-reuse

If we use a plain object to declare the state of the module, then that state object will be shared by reference and cause cross store/module state pollution when it's mutated.

Just change your address module state declaration from plain object definition to function definition:

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

And you're good to go!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.