Vue2.0为什么不能检查数组的变化,该怎么解决?
参考答案
为什么不能
Vue 2 用 Object.defineProperty 把数组的每个已存在索引转 getter/setter 是不现实的(数组元素数量动态变化、性能差),所以 Vue 2 的策略是:
- 对数组本身做
observe,但不拦截索引赋值与length; - 重写 7 个变异方法:
push/pop/shift/unshift/splice/sort/reverse,在方法内部ob.dep.notify()(arrayMethods拦截层); - 因此
arr[0] = x、arr.length = 0、arr[10] = y都不会触发更新; - 依赖数组的 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 渲染的表格里「不刷新」,就是这个原因。