D
D
Dmitry Volkhontsev2017-08-30 14:44:04
JavaScript
Dmitry Volkhontsev, 2017-08-30 14:44:04

What is the correct way to change data inside an array when using Vuex?

Good day.
There is vuex, which has a variable that stores an array of objects. We need to make it possible to change objects inside the array and all this would be immediately reflected in the Vue component. In the component itself, something like this code

computed:{
      view(){
        return this.$store.getters.getView;
      }
}

I tried similar code in Vuex
EDIT_VIEW_LIST(state, item){
  state.listView.forEach((elem,idx)=>{
    if(elem.id===item.id){
      elem=item;
    }
  })
}

and such
EDIT_VIEW_LIST(state, item){
  let idx=state.listView.findIndex((elem,idx)=>{
        return elem.id===item.id;
  });
  if(idx){
    state.listView[idx]=item;
  }
}

But the Vue component does not react to such changes. At the moment I solved the problem in the following way:
EDIT_VIEW_LIST(state, item){
  state.listView=state.listView.map((elem,idx)=>{
    return elem.id===item.id ? item : elem;
  })
}

But it seems to me that this is not quite the right way. What is the best way to do this array change?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kulakov, 2017-08-30
@DarkDD

Here is a description for working with arrays: https://ru.vuejs.org/v2/guide/list.html#Tracked...
The method should helpVue.set

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question