在Vue3中,v-model仍然可以用来实现父子组件的双向数据绑定。具体实现步骤如下:
- 在子组件中,使用props接收父组件传递的value和通过$emit触发的input事件。
<template>
<input :value="value" @input="$emit('update:modelValue', $event.target.value)">
</template>
<script>
export default {
props: {
value: {
type: String,
required: true
}
}
}
</script>
- 在父组件中使用子组件时,通过v-model绑定value以及监听子组件触发的update:modelValue事件。
<template>
<div>
<ChildComponent v-model="message"></ChildComponent>
<p>{{ message }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: ''
}
}
}
</script>
这样,父子组件之间就实现了双向数据绑定。
另外,Vue3中可以利用computed属性进一步简化父子组件双向绑定。具体实现步骤如下:
- 在子组件中,利用computed定义一个名为modelValue的属性,同时在props中定义value属性。
<template>
<input :value="modelValue" @input="updateValue">
</template>
<script>
export default {
props: {
value: {
type: String,
required: true
}
},
computed: {
modelValue: {
get() {
return this.value;
},
set(newValue) {
this.$emit('update:value', newValue);
}
}
},
methods: {
updateValue(event) {
this.modelValue = event.target.value;
}
}
}
</script>
- 在父组件中使用子组件时,利用v-bind绑定value属性并声明一个computed属性对应子组件的modelValue属性。
<template>
<div>
<ChildComponent :value="message" @update:value="newValue => message = newValue"></ChildComponent>
<p>{{ message }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: ''
}
},
computed: {
childModelValue: {
get() {
return this.message;
},
set(newValue) {
this.message = newValue;
}
}
}
}
</script>
这样,父子组件之间的双向绑定就可以通过computed属性来实现。