Appearance
修改 Vuex 中的 state 必须要在 mutation 中,否则将不能被监听到。
如果在 mutation 中修改的是引用类型,发现 getters 中没有触发改变,这是因为在修改这个 state 的时候,没有改变引用类型的地址,解决方法是对其进行浅拷贝 or 深拷贝后重新赋值。
js
export const state = () => {
student: {
}
};
export const mutations = {
setStudent(state, { key, value }) {
state.student[key] = value;
state.student = { ...state.student }; //必须要赋值才能被监听到变化
},
};
export const getters = {
copyStudent(state) {
return state.student;
},
};export const state = () => {
student: {
}
};
export const mutations = {
setStudent(state, { key, value }) {
state.student[key] = value;
state.student = { ...state.student }; //必须要赋值才能被监听到变化
},
};
export const getters = {
copyStudent(state) {
return state.student;
},
};