Make Vuex store data reactive in Vuejs

Tech:
Vuejs
Since:
1 year ago
Views:
6

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

Solution 1 - Using spread operator

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

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

Solution 2 - Using Vue.set

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

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