- 代码思路:
- 使用 Vue 的响应式数据和事件系统来实现双向数据绑定。
- 在父组件中定义数据,并通过 props 将数据传递给模态框组件。
- 模态框组件通过
$emit
触发事件,将数据变化通知给父组件,父组件监听事件并更新数据。由于使用了 Teleport 移动到 body
下,组件间的层级关系虽有变化,但 Vue 的事件系统依然有效。
- 关键代码片段:
<template>
<div>
<button @click="showModal = true">打开模态框</button>
<Modal :show="showModal" @update:show="showModal = $event" />
</div>
</template>
<script setup>
import Modal from './Modal.vue';
import { ref } from 'vue';
const showModal = ref(false);
</script>
<template>
<teleport to="body">
<div v-if="show" class="modal">
<div class="modal-content">
<button @click="closeModal">关闭</button>
</div>
</div>
</teleport>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps(['show']);
const emits = defineEmits(['update:show']);
const closeModal = () => {
emits('update:show', false);
};
</script>
<style scoped>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background-color: white;
padding: 20px;
border-radius: 5px;
}
</style>