从 Vue 3.4 开始,推荐的实现方式是使用 defineModel()
宏:
废话不多说,直接上代码
javascript
<!-- Son.vue -->
<script setup>
const model = defineModel()
</script>
<template>
<span>My input</span> <input v-model="model">
</template>
<!-- Parent.vue -->
<script setup>
import Child from './Child.vue'
import { ref } from 'vue'
const msg = ref('Hello World!')
</script>
<template>
<h1>{{ msg }}</h1>
<Child v-model="msg" />
</template>
多个v-model
javascript
<!-- Parent.vue -->
<UserName
v-model:first-name1="first"
v-model:last-name1="last"
/>
<!-- Son.vue -->
<script setup>
const firstName = defineModel('firstName1') //这里的参数就是父组件v-model后面的值
const lastName = defineModel('lastName1')
</script>
<template>
<input type="text" v-model="firstName" />
<input type="text" v-model="lastName" />
</template>
处理 自定义v-model 修饰符
javascript
<!-- Parent.vue -->
<MyComponent v-model.capitalize="myText" />
<!-- Son.vue -->
<script setup>
const [model, modifiers] = defineModel({
set(value) {
if (modifiers.capitalize) {
return value.charAt(0).toUpperCase() + value.slice(1)
}
return value
}
})
</script>
<template>
<input type="text" v-model="model" />
</template>