Need multiple instances of Vuex module for multiple Vue instances

霸气de小男生 提交于 2021-02-08 10:30:26

问题


I'm integrating Vue onto a site for forms, which means I have to create several instances of that Vue application if there are multiple forms on the page. All instances share the same Vuex store.

I created a Vuex module so that each Vue instance could have it's own local state. My main goal is to prevent one Vue instance from updating the state of another Vue instance.

Here's my Vuex module

export default {
  state() {
    return {
      stateObj: {...}
    }
  }
}

Creating my Vuex instance:

export default new Vuex.Store({
  modules: {
    form
  }
})

I was reading the Vuex docs and it says you need to use a function that returns the modules state, which is what I'm doing. However, when I update the module's state in one my Vue instances, it updates the all other Vue instance's module state.

Here's the section in the Vuex docs I am referring to.


回答1:


The reason this is happening is that you are not really creating multiple instances of form module or your store. You are essentially creating multiple instances of Vue applications, that is you are having multiple Root Vue Instances.

However, your store code clearly suggests that you are creating a single instance of Vuex store by exporting an instance like: export default new Vuex.Store({ /**/ }).

If you have multiple root instances i.e. multiple Vue applications, then you need multiple instances of the Vuex Store. Your code would be something like:

// store.js - Note: Do not return singleton store
export default function makeStore() {
  return new Vuex.Store({
    modules: { form }
  });
}

// main.js/root.js
import makeStore from './store.js';

// Creating multiple instances of root instance and Vuex store.
const app1 = new Vue({ store: makeStore() });
const app2 = new Vue({ store: makeStore() });

This should solve your problem. Though this design is not uncommon, you should still take a step back and think - what if you need to share data across all these apps? Since there are multiple instances, you cannot do that easily. As long as all these forms are working in isolation, it should be fine.

Alternately, if you have to really make single instance of your store, then consider changing your store design. You should have a single root instance/app and use v-for to generate multiple forms. Similarly, on the store side, you would have an array to maintain a collection of all the forms.



来源:https://stackoverflow.com/questions/55272189/need-multiple-instances-of-vuex-module-for-multiple-vue-instances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!