Vuex中的状态如果是引用类型,没有响应式
修改 Vuex 中的 state 必须要在 mutation 中,否则将不能被监听到。
如果在 mutation 中修改的是引用类型,发现 getters 中没有触发改变,这是因为在修改这个 state 的时候,没有改变引用类型的地址,解决方法是对其进行浅拷贝 or 深拷贝后重新赋值。
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
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
上次更新: 2023/12/16, 09:22:46