Make Vuex store data reactive in VueJs

Changing the Vuex store's data directly won't be reactive and the components consuming those won't update. There are two ways to make the store's data reactive.

Using spread operator

One way of making store data reactive, is using Javascript spread operator.

// State
export const state = () => ({
  obj1: { val_1: 1 }
});

// Mutation
export const mutations = {
  UpdateProperty(state) {
    state.obj1 = { ...state.obj1, val_2: 2 };
  }
};

Using Vue.set

Another way is using "Vue.set".

// State
export const state = () => ({
  obj1: { val_1: 1 }
});

// Mutation
export const mutations = {
  UpdateProperty(state) {
    Vue.set(state.obj1, "val_2", 2);
  }
};
1 year ago
Vue