Skip to content Skip to sidebar Skip to footer

Vuex - Update Entire Object Inside Array

Inside my Vuex mutation, I want to replace an array element in my state, as shown below: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.i

Solution 1:

You should use Vue.$set (or this.$set inside Vue instance):

UPDATE_MAILING(state, mailing) {
    let index = state.mailings.findIndex(item => item.id === mailing.id)
    Vue.$set(state.mailings, index, mailing)
}

Docs: Vue.js → Reactivity in Depth

Solution 2:

As described in the docs, you could use either Array.prototype.splice() or Vue.set() to reactively replace the array item:

mutations: {
  UPDATE_MAILING(state, mailing) {
    const index = state.mailings.findIndex(x => x.id === mailing.id)
    state.mailings.splice(index, 1, mailing)

    // OR:Vue.set(state.mailings, index, mailing)
  }
}

I prefer splice here, as it doesn't require importing Vue, which also makes it easier to test.

demo

Post a Comment for "Vuex - Update Entire Object Inside Array"