关于 vue 项目不能 watch 数组变化和对象变化的解决方案

415 阅读1分钟

vue 无法监听数组变化的情况

  1. 利用索引直接设置一个数组项时,例如:arr[indexOfItem] = newValue;
  2. 修改数组的长度时,例如:arr.length = newLength;

vue 无法监听数组变化的解决方案

  1. set方法: this.$set(arr, index, newVal);
  2. splice方法: this.arr.splice(index, number, newVal);
  3. 临时变量方法:let temp = [...this.arr]; temp[index] = newVal; this.arr = temp;

vue 无法监听对象变化的情况

  1. vue 可以监听直接赋值的对象;
  2. vue 不能监听对象属性的添加、修改、删除;

vue 监听对象的解决方法

  1. set方法新增属性:this.$set(object, key, value);
  2. 深度监听方法:deep: true;
  3. Object.assign 方法:this.watchObj = Object.assign({}, this.watchObj, value);