E
E
egyptForce2018-09-14 12:55:13
Vue.js
egyptForce, 2018-09-14 12:55:13

How to mutate state correctly?

<list>
  <item v-for="item in items" :item="item" :key="item.id">...</item>
</list>

items = [{
  id: 1,
  age: 24,
  public: 0
}, {
  id: 2,
  age: 23,
  public: 0
}, {
  id: 3,
  age: 52,
  public: 1
}]

there is an array of objects, each element of which, through props, in a cycle, is passed to the component. on the user's action, inside this component, you need to change the field of the corresponding object
, now I know how to do it in two ways, both work, but for some reason it seems that the second option is too easy and it has pitfalls.
props: ['item'],
methods: {
  updatePublic1() {
    this.$store.commit('update:public1', this.item.id)
  },
  updatePublic2() {
    this.$store.commit('update:public2', this.item)
  }
}

'update:public1'(state, id) {
  const item = state.items.find(el => el.id === id)
  item.public = !item.public
}

'update:public2'(state, item) {
  item.public = !item.public
}

I would like to ask those who are more experienced in view, what is the second method bad for? pysy: the code is a bit exaggerated for ease of understanding

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question