- v-model的本质是 value 属性和 input 事件
<input v-model='firstName' >
等价于
<input :value="firstName" @input="firstName = $event.target.value" />
- 组件上使用v-model
v-model 默认情况下会使用modelValue作为属性 update:modelValue 作为事件
所以子组件中直接 接收 modelValue 属性 和 update:modelValue 事件即可
父组件 parent.vue
<template>
<child v-model='firstName' />
</template>
<script setup>
import child from './child.vue'
import {ref} from 'vue'
const firstName = ref('')
</script>
子组件 child.vue
<template>
<input
type="text"
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
</template>
<script setup>
defineProps(["modelValue"]);
defineEmits(["update:modelValue"]);
</script>
- 指定特定参数来替换v-model的默认属性 modelValue
父组件 parent.vue
<template>
<child v-model:first='firstName' />
</template>
<script setup>
import child from './child.vue'
import {ref} from 'vue'
const firstName = ref('')
</script>
子组件 child.vue
<template>
<input
type="text"
:value="first"
@input="$emit('update:first', $event.target.value)"
/>
</template>
<script setup>
defineProps(["first"]);
defineEmits(["update:first"]);
</script>
4.子组件绑定多个 v-model
父组件 parent.vue
<template>
<child v-model:first='firstName' v-model:last='lastName' />
</template>
<script setup>
import child from './child.vue'
import {ref} from 'vue'
const firstName = ref('')
const lastName = ref('')
</script>
子组件 child.vue
<template>
<input
type="text"
:value="first"
@input="$emit('update:first', $event.target.value)"
/>
<input
type="text"
:value="last"
@input="$emit('update:last', $event.target.value)"
/>
</template>
<script setup>
defineProps(["first","last"]);
defineEmits(["update:first","update:last"]);
</script>