Home > Blockchain >  How to create isolated Vuex states for every initialized instance of a component in Vue?
How to create isolated Vuex states for every initialized instance of a component in Vue?

Time:01-07

I'm new to Vue.

I see people suggest that we need to use a Vuex module for components to store their state data so we can access that data in the parent component.

For example, I have MarkdownEditor.vue component and I'll need to access its data from the parent. I store the state in a Vuex module, e.g markdownEditorStore.js... I can access this state in the parent component easily, like, this.$store.state.markdownEditor.XYZ.

That's OK. But what if I have n number of MarkdownEditor components and need isolated states for each of them? This is very basic problem, but how can I handle this?

I need a solution based on instances of module, not a module based one.

CodePudding user response:

What i understand from your question is that you want a individual state for each component which you can achieve by creating a separate module with namespace=true for each component https://vuex.vuejs.org/guide/modules.html#namespacing

CodePudding user response:

The module feature is to split the logic between different domains(Editor in your case is one module). Not for the instances themselves.

The rule of thumb is that the parent that will connect with the Vuex store passes down to MarkdownEditor.vue the data necessary to load. Ideally, MarkdownEditor is able to load just with the props received from the parent. This is a good practice of splitting the visual from the state. Making it easier to test and a clear component API.

Even though you have N possible ME(MarkdownEditor) instances, either you show one at once or multiple. For both cases, you can have a MarkdownEditorDataStore that will hold all the data needed.

Then you just need to access the correct piece of data for each ME instance. And that's up to your store and components structure. Two ways I can think of is that either you have an array for the N ME instance like editors: [ { id: 1, title: X}, { id: 2, title: Y } ] or an object that holds all the data { editors: { 1: {id: 1, title: X }, 2: { id: 2, title: Y } }.

Either you get the data via this.$store.state.MarkdownEditorDataStore.editors[myID] or this.$store.state.MarkdownEditorDataStore.editors.find(id => myID === id)

You can have a data property holding the currentEditorId in case you show just one instance at a time. Even better to use a getter in that case to show the actualCurrentEditorObject.

  •  Tags:  
  • Related