v-model
在vue3中v-model是破环性更新
v-model其实是一个语法糖,通过props和emit组成
子组件要修改父组件的值
- prop:
value
->modelValue
; - 事件:
input
->update:modelValue
; v-bind
的.sync
修饰符和组件的model
选项已移除
v-model的更多用法
- 新增 支持多个v-model
- 新增 支持自定义 修饰符 Modifiers
单个v-model
案例:
父组件
<script setup lang="ts">
// 通过v-model来实现父子组件之间的双向绑定
import A from './components/A.vue'
import {ref} from "vue";
const flag = ref(true)
</script>
<template>
<div class="switch">
{
{flag}}
<button @click="flag = !flag">切换</button>
</div>
<transition
enter-active-class="animate__animated animate__backInDown"
leave-active-class="animate__animated animate__backOutDown">
<A v-model="flag"></A>
</transition>
</template>
<style scoped>
.switch {
width: 200px;
margin: 5px auto;
}
</style>
子组件
<script setup lang="ts">
defineProps<{
modelValue:boolean
}>()
const emit = defineEmits<{
(e:'update:modelValue', value: boolean): void
}>()
function submit() {
emit('update:modelValue', false)
}
</script>
<template>
<div class="container" v-if="modelValue">
<div>
<span>请输入:</span>
<input type="text">
</div>
<button @click="submit">提交</button>
</div>
</template>
<style scoped>
.container {
width: 500px;
height: 500px;
background-color: #ccc;
border: 1px solid grey;
margin: 0 auto;
}
.header {
height: 50px;
background-color: #eee;
border: 1px solid grey;
}
.body {
height: 400px;
background-color: #ddd;
border: 1px solid grey;
}
.footer {
height: 50px;
background-color: #eee;
border: 1px solid grey;
}
</style>
也可以给一个组件绑定多个v-model
案例:
父组件
<A v-model="