不要在突变处理程序之外改变 Vuex 存储状态



我正在尝试覆盖商店中名为 device 的数组中的对象。 突变 saveState 接收一个设备,如果它不存在于设备数组中,它将推送对象,但如果它已经存在,它只会用收到的设备替换它。 我尝试寻找解决方案将近一天,但我无法解决我的代码问题。

商店.设备.js

export const state = () => ({
device: []
})
export const mutations = {
saveState(state, device) {
var index = state.device.findIndex(dev => dev.id == device.id)
index === -1 ? state.device.push(device) : (state.device[index] = device)
}
}
export const getters = {
getStateById: state => id => {
return state.device.find(dev => dev.id === id)
}
}

您遇到的问题是,当您直接尝试像使用state.device[index] = device一样设置数组索引时,Vue 无法检测到状态更改。

为此,他们提供了 Vue.set,它允许您在某个索引处更新数组。它是这样用的:

//Vue.set(array, indexOfItem, newValue)
index === -1 ? state.device.push(device) : Vue.set(state.device, index, device);

您可以在文档中阅读有关它的信息

此处

最新更新