vue实现数组
Vue 中数组的实现方法
在 Vue 中,数组的操作需要特别注意响应式更新。Vue 对数组的变异方法进行了封装,确保数组变化能够触发视图更新。以下是常见的数组操作方法:
响应式数组方法
Vue 封装了以下数组的变异方法,调用它们会触发视图更新:
push()pop()shift()unshift()splice()sort()reverse()
示例代码:
data() {
return {
items: ['a', 'b', 'c']
}
},
methods: {
addItem() {
this.items.push('new item') // 触发响应式更新
}
}
非变异方法替换
对于不会改变原数组的方法(如 filter(), concat(), slice()),需要将返回的新数组赋值给原变量:
this.items = this.items.filter(item => item !== 'a')
直接索引修改问题
直接通过索引修改数组元素不会触发视图更新:
this.items[0] = 'new value' // 不会触发更新
解决方案
-
使用
Vue.set或this.$set:this.$set(this.items, 0, 'new value') -
使用
splice方法:this.items.splice(0, 1, 'new value')
数组响应式原理
Vue 通过重写数组的原型方法实现响应式。当观测一个数组时,Vue 会:
- 拦截数组的变异方法
- 在方法执行后通知依赖更新
- 对于非变异方法,需要重新赋值才能触发更新
注意事项
-
避免直接修改数组长度:
this.items.length = 0 // 不会触发更新 -
正确清空数组的方法:
this.items = [] this.items.splice(0) -
深层数组的响应式处理需要额外注意,必要时使用
Vue.set或this.$set确保嵌套属性的响应性。







