1. 父组件代码
<template>
<button @click="visible = !visible">父组件开关按钮</button>
<Child v-model="visible" />
</template>
<script setup lang="ts">
import { ref } from "vue"
import Child from "./child.vue"
const visible = ref<boolean>(false)
</script>
2. 子组件代码
<template>
<div class="child" v-show="props.modelValue">
<div>子组件文字</div>
<button @click="updateModelValue(false)">子组件关闭</button>
</div>
</template>
<script lang="ts" setup>
const emit = defineEmits(['confirm','update:modelValue'])
interface Props {
modelValue:boolean
}
const props = defineProps<Props>()
function updateModelValue(value:boolean){
emit("update:modelValue",value)
}
</script>
<style scoped>
.child{
border: 1px solid #000;
}
</style>
3. 解析
父组件使用 v-model 向子组件传值。
需要注意的是,子组件是使用 prop.modelValue 读取父组件 v-model 传过来的值,子组件通过 emit("update:modelValue",value) 改变 v-model 的值,此时父组件的值也会被改变,体现了双向绑定