vue实现数组监听
Vue 中实现数组监听的方法
Vue 通过重写数组的原型方法来实现对数组变化的监听。由于 JavaScript 的限制,Vue 无法直接通过 Object.defineProperty 监听数组索引的变化。以下是几种常见的实现方式:
使用 Vue.set 或 this.$set
对于直接通过索引修改数组元素的情况,需要使用 Vue.set 或 this.$set 来确保修改能被响应式系统检测到。

this.$set(this.array, index, newValue);
// 或
Vue.set(this.array, index, newValue);
使用数组的变异方法
Vue 重写了数组的以下变异方法,这些方法会触发视图更新:
push()pop()shift()unshift()splice()sort()reverse()
this.array.push(newItem); // 自动触发响应式更新
监听数组变化
可以通过 watch 监听数组的变化:

watch: {
array: {
handler(newVal, oldVal) {
// 处理数组变化
},
deep: true // 深度监听
}
}
使用计算属性
如果需要基于数组的变化生成新的数据,可以使用计算属性:
computed: {
filteredArray() {
return this.array.filter(item => item.condition);
}
}
使用 Vue 3 的响应式 API
在 Vue 3 中,可以使用 reactive 和 ref 来创建响应式数组:
import { reactive, ref } from 'vue';
const array = reactive([]);
// 或
const array = ref([]);
注意事项
- 直接通过索引修改数组元素(如
this.array[index] = newValue)不会触发响应式更新。 - 直接修改数组长度(如
this.array.length = newLength)也不会触发更新。 - 对于嵌套数组或对象,需要确保它们也是响应式的。






