Categories
Vue Answers

Is state.array.push reactive in a Vue.js Vuex mutation?

Spread the love

No, directly pushing items into an array using state.array.push() inside a Vuex mutation won’t trigger reactivity in Vue.js.

This is because Vue cannot detect mutations to arrays when we directly modify them, such as using methods like push(), pop(), splice(), etc.

To maintain reactivity, we should use Vue’s set or splice methods, or if we’re using Vuex, we should return a new array with the updated values. Here’s how we can do it:

// In our Vuex store
mutations: {
  addItem(state, item) {
    state.array = [...state.array, item]; // This maintains reactivity by returning a new array with the added item
  }
}

Or using Vue’s set method:

// In our Vuex store
mutations: {
  addItem(state, item) {
    Vue.set(state.array, state.array.length, item);
  }
}

Using Vue.set or returning a new array ensures that Vue can detect the change and trigger reactivity appropriately. This is important especially if state.array is being watched or bound in any Vue components.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *