vue实现数组
vue实现数组操作
在Vue中操作数组需要使用Vue提供的响应式方法,直接修改数组元素不会触发视图更新。以下是常见的数组操作方法:
添加元素
使用push、unshift或splice方法添加元素:
this.array.push(newItem) // 末尾添加
this.array.unshift(newItem) // 开头添加
this.array.splice(index, 0, newItem) // 指定位置插入
删除元素
使用pop、shift或splice方法删除元素:
this.array.pop() // 删除末尾元素
this.array.shift() // 删除开头元素
this.array.splice(index, 1) // 删除指定位置元素
修改元素 使用Vue.set或数组索引直接修改:
Vue.set(this.array, index, newValue)
// 或
this.$set(this.array, index, newValue)
替换数组 直接赋值为新数组:
this.array = newArray
过滤数组 使用filter方法创建新数组:
this.array = this.array.filter(item => item.condition)
排序数组 使用sort方法排序:
this.array.sort((a, b) => a.property - b.property)
vue数组响应式原理
Vue通过重写数组的变异方法实现响应式,这些方法包括:
push()pop()shift()unshift()splice()sort()reverse()
对于非变异方法如filter、concat、slice等,需要将返回的新数组赋值给原数组才能触发更新。
vue3数组操作变化
Vue3中使用Proxy实现响应式,可以直接通过索引修改数组元素:
const state = reactive({
list: [1, 2, 3]
})
state.list[0] = 99 // 在Vue3中能触发响应
但仍推荐使用扩展运算符或Array.from创建新数组:
state.list = [...state.list, newItem]
常见问题解决
视图不更新 确保使用Vue提供的变异方法或Vue.set,避免直接通过索引修改数组。
性能优化 对于大型数组,使用Object.freeze冻结非响应式数据,或考虑虚拟滚动方案。
数组监听 使用watch深度监听数组变化:
watch(
() => [...this.array],
(newVal, oldVal) => {
// 处理变化
},
{ deep: true }
)






