【问题标题】:do not mutate vuex store state outside mutation handlers不要在突变处理程序之外改变 vuex 存储状态
【发布时间】:2020-10-05 05:08:11
【问题描述】:

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

store.device.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)
  }
}

【问题讨论】:

    标签: vue.js vuex nuxt.js


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-09-24
      • 2018-02-13
      • 2022-01-09
      • 2020-03-30
      • 2023-03-09
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      相关资源
      最近更新 更多