'why state and this.state show different value in mutation Vuex
i m using Vue3 and Vuex, here is the version.
"vue": "^3.0.5",
"vuex": "^4.0.0",
I was trying to reset the state in a module by using the default state. But I found either I assign the state equal to the return value of the getDefault function or destructure the state and return value, the state and this._state shows a different value. the value in this._state still shows the previous value (did not get updated).
However, if I use the way that I commented in the resetState, the value of state and this._state are the same.
I would like to know why are the results different by using different ways to reset the state.
Here is the code:
const getDefaultState = () => {
return {
vueInstances: {},
};
};
export default {
namespaced: 'test',
state: getDefaultState(),
mutations: {
resetState(state) {
// const newState = getDefaultState();
// for (const stateField in newState) {
// if (newState.hasOwnProperty(stateField)) {
// state[stateField] = newState[stateField];
// }
// }
state = getDefaultState() // state = [...state, ...getDefaultState()]
console.log(state);
console.log(this._state);
},
addVueInstance(state, payload) {
state.vueInstances = {
...state.vueInstances,
[payload.name]: payload.instance,
};
},
},
actions: {
addVueInstance({ commit, state }, payload) {
if (state[payload.name]) {
return;
}
commit('addVueInstance', payload);
},
},
};
here is result
// console.log(state)
{
"vueInstances": {}
}
// console.log(this._state)
{
vueInstances:{
clientPopup: {_uid: 0, _component: {…}, _props: null, …}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
