vue实现数组监听
Vue 实现数组监听的方法
Vue 通过重写数组的原型方法来实现对数组变化的监听,确保数组操作能够触发视图更新。以下是具体实现方式和注意事项:
重写数组方法
Vue 对以下数组方法进行了拦截和重写,使其能够触发响应式更新:
push()pop()shift()unshift()splice()sort()reverse()
重写后的方法会在调用原生数组方法后,通知依赖进行更新。例如:

const originalArrayProto = Array.prototype
const arrayProto = Object.create(originalArrayProto)
['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(method => {
arrayProto[method] = function(...args) {
const result = originalArrayProto[method].apply(this, args)
const ob = this.__ob__
ob.dep.notify()
return result
}
})
直接修改数组索引
直接通过索引修改数组元素不会触发响应式更新:
this.items[index] = newValue // 不会触发更新
需要改用 Vue.set 或数组的 splice 方法:

Vue.set(this.items, index, newValue)
// 或
this.items.splice(index, 1, newValue)
监听数组长度变化
修改数组长度属性也不会触发更新:
this.items.length = newLength // 不会触发更新
应使用 splice 方法:
this.items.splice(newLength)
深层数组监听
对于嵌套数组,Vue 会递归地对每个元素进行响应式处理:
data() {
return {
nestedArray: [
[1, 2],
[3, 4]
]
}
}
注意事项
- 使用
Vue.set或this.$set添加新元素到数组 - 避免直接设置数组长度
- 对于大型数组,考虑使用不可变数据方式更新
- 对象数组的属性修改需要使用
Vue.set或确保属性是响应式的
Vue 的数组监听机制使得开发者能够方便地处理数组变化,同时需要注意某些特殊情况的处理方式。






