在Vue2中,父组件通过v-model
传递一个对象给子组件,子组件需要将多个输入框绑定到该对象的属性并保持同步。以下是实现步骤及代码示例:
v-model
绑定对象到子组件。props
接收该对象。get
和set
方法:get
方法返回父组件对象的对应属性值。set
方法触发input
事件,返回更新后的整个对象。父组件:
<template>
<div>
<child-component v-model="formData"></child-component>
<p>父组件中的数据:{{ formData }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
formData: {
name: '张三',
age: 25
}
};
}
};
</script>
子组件:
<template>
<div>
<input type="text" v-model="name">
<input type="number" v-model="age">
</div>
</template>
<script>
export default {
props: {
value: {
type: Object,
required: true
}
},
computed: {
name: {
get() {
return this.value.name;
},
set(newVal) {
// 触发input事件,更新父组件对象
this.$emit('input', { ...this.value, name: newVal });
}
},
age: {
get() {
return this.value.age;
},
set(newVal) {
this.$emit('input', { ...this.value, age: newVal });
}
}
}
};
</script>
get
方法获取父组件对象的属性值,set
方法在值变化时触发input
事件,传递合并后的新对象。v-model
自动监听input
事件,更新整个对象,确保所有属性保持响应式。value
,而是通过事件通知父组件更新,符合Vue数据流规范。此方法实现了父子组件间的双向数据绑定,同时保持代码简洁和响应式特性。