实现vue数组双向绑定
Vue 数组双向绑定的实现方法
Vue 通过数据劫持和发布-订阅模式实现数据的双向绑定,但直接修改数组的某些方法(如索引赋值)无法触发视图更新。以下是实现数组双向绑定的几种方法:
使用 Vue.set 或 this.$set
Vue 无法检测直接通过索引修改数组元素,需使用 Vue.set 或实例方法 this.$set 触发响应式更新。
this.$set(this.array, index, newValue);
使用数组变异方法
Vue 重写了部分数组方法(如 push, pop, splice 等),调用这些方法可触发视图更新。
this.array.splice(index, 1, newValue);
使用 .sync 修饰符(Vue 2.x)
在父子组件间实现数组的双向绑定,可通过 .sync 修饰符和 $emit 更新父组件数据。
// 父组件
<child-component :array.sync="parentArray"></child-component>
// 子组件
this.$emit('update:array', newArray);
使用 v-model(Vue 3 推荐)
Vue 3 支持多个 v-model 绑定,可直接实现数组的双向绑定。
// 父组件
<child-component v-model:array="parentArray"></child-component>
// 子组件
props: ['array'],
emits: ['update:array'],
methods: {
updateArray(newArray) {
this.$emit('update:array', newArray);
}
}
使用 computed 和 watch
通过计算属性和监听器手动实现数组的双向绑定逻辑。
data() {
return {
internalArray: []
};
},
props: ['array'],
watch: {
array: {
immediate: true,
handler(newVal) {
this.internalArray = [...newVal];
}
},
internalArray: {
deep: true,
handler(newVal) {
this.$emit('update:array', [...newVal]);
}
}
}
注意事项
- Vue 2.x 中直接通过索引修改数组(如
this.array[0] = value)不会触发更新。 - 对于嵌套数组或对象,需确保使用响应式方法修改内部属性。
- Vue 3 的响应式系统基于 Proxy,对数组操作的支持更全面,但仍推荐使用标准方法。







