javascript - Vuex - Update entire object inside array - Stack Overflow

Inside my Vuex mutation, I want to replace an array element in my state, as shown below:UPDATE_MAILING(

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742401398a4436981.html

相关推荐

  • javascript - Vuex - Update entire object inside array - Stack Overflow

    Inside my Vuex mutation, I want to replace an array element in my state, as shown below:UPDATE_MAILING(

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信