上一篇博客有提到直接改变vuex中的值会报错,现在详细记录一下这个错误,首先看一下错误
在这里插入图片描述
这是因为直接操作vuex中的数据没有通过mutations去更新state而报的错误,如果在一个组件中初始化数据赋值state中的数据,如下

 this.modelList = store.state.sd.frame.modelList

然后在方法中改变了modelList(如增删改),如下方法

 changeModel(model) {
      if (model) {
        model.modelChosen = !model.modelChosen
        if (model.modelChosen) {
          this.modelList.push({ name: model.name, showCode: model.showCode, width: model.width })
        } else {
          this.modelList.splice(
            this.modelList.findIndex((item) => item.name === model.name),
            1
          )
        }
      }

这样,就会报上述错误了,但是代码还是可以正常执行的,所以,在复制时候需要给后面加上slice()进行拷贝一下就好了,像这样

 this.modelList = store.state.sd.frame.modelList.slice()

然后通过mutations更新vuex的数据

 store.commit('sd/frame/setModelList', this.modelList)

这样错误就解决了,相信我,一定要加slice(),不加会死人的

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐