← 返回完整题库
vue.js困难

Vue2.0为什么不能检查数组的变化,该怎么解决?

参考答案

为什么不能

Vue 2 用 Object.defineProperty 把数组的每个已存在索引转 getter/setter 是不现实的(数组元素数量动态变化、性能差),所以 Vue 2 的策略是:

  1. 对数组本身做 observe,但不拦截索引赋值与 length;
  2. 重写 7 个变异方法:push/pop/shift/unshift/splice/sort/reverse,在方法内部 ob.dep.notify()(arrayMethods 拦截层);
  3. 因此 arr[0] = x、arr.length = 0、arr[10] = y 都不会触发更新;
  4. 依赖数组的 watcher 是在 getter 里通过 childOb.dep.depend() 收集的,只有走变异方法才会 notify。

解决方式

// 1. 索引赋值用 $set
this.$set(this.list, 0, newItem)
// 2. 用变异方法
this.list.splice(0, 1, newItem)
// 3. 整体替换(最常用)
this.list = this.list.map((it, i) => i === 0 ? newItem : it)
// 4. Vue.delete / splice 删除
this.$delete(this.list, 1)

补充说明

  • filter/concat/map/slice 等非变异方法返回新数组,赋值给原变量后能触发更新(因为是 setter 赋值);
  • Vue 2 里 arr.length = 0 也不触发,用 arr.splice(0) 代替;
  • 数组里嵌套对象的属性修改(arr[0].name = 'x')是能触发的,因为对象属性有 getter/setter;
  • Vue 3 用 Proxy,arr[index] = x、arr.length = n 都能拦截,无需 $set。

高频踩坑

this.list[index] = newVal(Vue 2)在 v-for 渲染的表格里「不刷新」,就是这个原因。

本题来自 计算机知识面试题库,共 921 道题。