v-model="state" 本质是 Vue 提供的一个语法糖(syntactic sugar),用于简化「父子组件之间的双向绑定」。
一、基础等价转换
html
<Child v-model="state" />
等价于:
html
<Child
:modelValue="state"
@update:modelValue="val => state = val"
/>
二、子组件实现示例
- 子组件(Child.vue)
html
<template>
<input
:value="modelValue"
@input="handleInput"
/>
</template>
<script setup>
const props = defineProps({
modelValue: String
})
const emit = defineEmits(['update:modelValue'])
const handleInput = (e) => {
emit('update:modelValue', e.target.value)
}
</script>
- 父组件
html
<template>
<Child v-model="state" />
<p>{{ state }}</p>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const state = ref('hello')
</script>