v-model
(1) 在 3.x 中,自定义组件上的默认 v-model
相当于传递了 modelValue
prop 并接收子组件抛出的 update:modelValue
事件:
父组件
<template>
<button @click.prevent="show = !show" class="btn">开关{{show}}</button>
<child v-model="show"></child>
</template>
<script setup lang='ts'>
import child from "./child.vue";
import {ref} from 'vue'
const show = ref(false)
</script>
<style>
</style>
子组件
<template>
<div v-if="modelValue" class="dialog">
<div class="dialog-header">
<div @click="close">关闭</div>
</div>
</div>
</template>
<script setup lang="ts">
interface Props{
modelValue:boolean,
}
withDefaults(defineProps<Props>(),{
modelValue:true
})
const emits = defineEmits(['update:modelValue'])
const close = ()=>{
emits('update:modelValue',false)
}
</script>
(2)自定义 绑定多个v-model
父组件
<template>
<button @click.prevent="show = !show" class="btn">开关{{show}}----标题:{{title}}</button>
<child v-model="show" v-model:title="title"></child>
</template>
<script setup lang='ts'>
import child from "./child.vue";
import {ref} from 'vue'
const show = ref(false)
const title = ref<string>('父组件标题')
</script>
<style>
</style>
子组件
<template>
<div v-if="modelValue" class="dialog">
<div class="dialog-header">
<div class="title">{{title}}</div>
<div @click="close">关闭</div>
</div>
</div>
</template>
<script setup lang="ts">
interface Props{
modelValue:boolean,
title?:string
}
withDefaults(defineProps<Props>(),{
modelValue:true,
title:"默认标题"
})
const emits = defineEmits(['update:modelValue','update:title'])
const close = ()=>{
emits('update:modelValue',false)
emits('update:title','子组件传递过来的title')
}
</script>