S
S
SimBioT192021-01-26 17:58:49
JavaScript
SimBioT19, 2021-01-26 17:58:49

How to avoid props mutation?

An array of instances of some class items[] lies in vuex, is used in many places and at the same time is displayed in an editable list:

<ul>
<v-list-component :item=item v-for=item in items/>
</ul>


Inside the v-list-component API methods are called, each item changes.
And inside this component, I directly change the properties of the passed item, conditionally:

computed: {
 _value: {
  get() {
   return this.item.name;
  },
  set(val) {
    this.item.name = val; // Ошибка mutating prop
    ...
  }
}


I understand that this is wrong, but what should I do?
Emit events with an update to the top so that they deal with the changes there?

It's just that if my v-list-component is used in several different places, I will have to write listener methods everywhere, and this is code duplication.

How will it be right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2021-01-26
@Rsa97

Vuex

S
Sergey Levchenko, 2021-01-26
@nuykon

I don't know what you want to achieve. You can decide in different ways. But since you have items in vuex, then at least you need to use - mutations / actions
on the example of your code:

set(val) {
    this.$store.dispatch('updateItem', { id: this.item.id, val });
  }

well, in the store, of course, it will be necessary to write an action and a mutation
and it is worth setting a key for the elements in the lists , otherwise problems may arise when rerendering another option without computed: copy what came from props to the local state (data()), it can be overwritten and errors will not, add a watch to change the property in data and there again call action from vuex <v-list-component :key="item.id">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question