How to manage nested arrays in Vuex Store and pass it trough component How to manage nested arrays in Vuex Store and pass it trough component vue.js vue.js

How to manage nested arrays in Vuex Store and pass it trough component


The best thing to do is to avoid nested structures. This is an established pattern in other global state single state tree systems like redux as well. But no need for Redux here. Normalizing the data is a good idea, yes - and the patterns that are used in redux for this stuff are applicble to vuex as well.

Normalization bascially means that you turn this:

planning : [    {        name : 'monday',        meetings : [            {                name : 'morning',                value : ''            }, {                name : 'noon',                value : ''            }, {                name : 'evening',                value : ''            }]    },    {        name : 'tuesday',        meetings : [            {                name : 'morning',                value : ''            }, {                name : 'noon',                value : ''            }, {                name : 'evening',                value : ''            }]    },    ...}]

into this :

planning: {  name: [monday,tuesday],  meetings: {    monday: { id: 'monday', name: [1,2,3] },    tuesday: { id: 'tuesday', name: [4,5,6] },  }},name : {   meetings : {    1: {id: 1, text: 'morning' , value: ''},    2: {id: 2, text: 'noon' , value: ''},    3: {id: 3, text: 'evening' , value: ''},            4: {id: 4, text: 'morning' , value: ''},    5: {id: 5, text: 'noon' , value: ''},    5: {id: 6, text: 'evening' , value: ''},            }}

And now you can implement easy getters and setters into Vuex Store.It seems like it’s more complicated, and in a way it is, a little. But the advantage is that for updates, you will not have to worry about any nesting-related issues when writing mutations.

Ex: if you need a sorted array of all planning, you write a getter:

planningArray (state) => {  return state.planning.list.map {             name => state.planning.meetings[name]  }}

Using this you do not need to pass props. For every change you push the data into the Store and retrieve it into another component using "computed/methods"


If I'm not mistaken, you're trying to save a value from an input into vuex state which is meetings.value object.

First of all, you need to bind your input into separate object. Kind this way:

data () {  return {    value: null  }}

then in your template section,

<input type="text" v-model="value"><button @click="onValueSaved"></button>

and you need to declare a method to saved the value into vuex state,

methods: {   onValueSaved () {     this.$store.commit('SET_MEETING_VALUE', this.value)   }}