2

According to the Official docs, vuex mutations has some limitation in reactivity.

When adding a new property to an object we have to do,

Vue.set(obj, 'newProp', 123)

This is fine. But how do we add new array property and push elements to that without breaking the reactivity?

This is what I have done up to now. This is working fine but the problem is this is not reactive. Getters can't recognize the changes happen to the state.

set_add_ons(state, payload) {
        try {

            if (!state.tour_plan[state.tour_plan.length - 1].add_ons) {
                state.tour_plan[state.tour_plan.length - 1].add_ons = [];
            }
            state.tour_plan[state.tour_plan.length - 1].add_ons.push(payload);


        } catch (error) {
            console.log("ERR", error)
        }
    },

How do I convert this to a code which is reactive?

1 Answer 1

1

You can use Vue.set to create the add_ons attribute to make it reactive; It should work for array too:

Vue.set(state.tour_plan[state.tour_plan.length - 1], 'add_ons', []);

Demo:

new Vue({
  el: '#app',
  data: {
    items: [{ id: 0 }]
  },
   methods: {
    addArray () {
      if (!this.items[this.items.length-1].add_on)
        this.$set(this.items[this.items.length - 1], 'add_on', [])
      this.items[this.items.length - 1].add_on.push(1)
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <button v-on:click="addArray">
    Add 1 to add_on create if not exists
  </button>
  <div v-for="item in items">add_on content: {{ item.add_on }}</div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.