vue3里面子组件和父组件双向绑定
时间: 2023-11-11 21:56:26 浏览: 68
在Vue 3中,子组件和父组件之间的双向绑定是通过使用`v-model`指令实现的。`v-model`指令将父组件的属性与子组件的属性进行绑定,使得在父组件中修改属性时,子组件也会相应地进行更新。
为了实现双向绑定,需要在子组件中使用`props`接收父组件的属性,并且在子组件中使用`$emit`方法触发一个自定义事件来更新父组件的属性。
下面是一个简单的示例,演示了父组件和子组件之间的双向绑定:
```html
<!-- 父组件 -->
<template>
<div>
<p>父组件属性:{{ parentValue }}</p>
<ChildComponent v-model="parentValue"></ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
data() {
return {
parentValue: '',
};
},
};
</script>
<!-- 子组件 -->
<template>
<div>
<p>子组件属性:{{ childValue }}</p>
<input v-model="childValue">
</div>
</template>
<script>
export default {
props: ['value'],
emits: ['update:value'],
data() {
return {
childValue: this.value,
};
},
watch: {
childValue(newValue) {
this.$emit('update:value', newValue);
},
value(newValue) {
this.childValue = newValue;
},
},
};
</script>
```
在上面的示例中,父组件的`parentValue`通过`v-model`指令与子组件的`childValue`进行双向绑定。当子组件中的输入框内容改变时,会触发`childValue`的更新,并通过`$emit`方法触发`update:value`事件,从而更新父组件的`parentValue`属性。同时,当父组件的`parentValue`发生变化时,子组件通过`watch`监听到`value`属性的变化,并将其赋值给`childValue`,从而保持双向更新。