admin管理员组

文章数量:1336189

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?

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?

Share edited Mar 26, 2019 at 5:15 tony19 139k23 gold badges277 silver badges347 bronze badges asked Mar 21, 2019 at 19:16 Caio KawasakiCaio Kawasaki 2,9507 gold badges38 silver badges73 bronze badges 4
  • Instead of doing it inside mutation, you can do the same inside getters! – Varit J Patel Commented Mar 30, 2019 at 11:24
  • As far as I understood if any changes happen to you array(inside state) it should be automatically update in your template html. To acheive this whatever the array you want to change get that array from state in puted function. (In puted whenever its dependecy(here your array) changes it will automatically update template html) – Pallamolla Sai Commented Apr 1, 2019 at 5:02
  • This link might help. vuejs/v2/guide/puted.html#Basic-Example – Pallamolla Sai Commented Apr 1, 2019 at 5:08
  • could you please tell me is my ment helped?? Did i understand question correctly? – Pallamolla Sai Commented Apr 1, 2019 at 6:45
Add a ment  | 

2 Answers 2

Reset to default 8

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

本文标签: javascriptVuexUpdate entire object inside arrayStack Overflow