简体   繁体   中英

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.id});

    state.mailings[index] = mailing
}

But this does not update my template bound to this array. How can I reactively update the array element?

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

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

i want to tell you that if you want to operator Array type ,you had better use mthod like splice slice pop push shift unshift,only you use thesel,the template can bound to your array. Don't use array[index] to operator; hope to help you sincerly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM