在 Vue 3 中,我们可以使用 Composition API 来更简洁地封装和管理组件的状态和逻辑。接下来,我会为您展示如何封装一个基本的 Modal 对话框组件。
1. 创建 Modal 组件
首先,我们创建一个新文件 Modal.vue
:
<template>
<div v-if="isOpen" class="modal-overlay">
<div class="modal">
<slot></slot>
<button @click="closeModal">关闭</button>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'Modal',
setup() {
const isOpen = ref(false);
const closeModal = () => {
isOpen.value = false;
}
return {
isOpen,
closeModal
}
}
}
</script>
<style>
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
display: flex;
align-items