这是个很好的问题!设计一个 Vue 3.0 Modal 时,我建议按照可复用、高扩展、简洁的原则来实现。下面我给你一个清晰的设计思路,涵盖组件拆分、使用方式以及 Vue 3 中特性(如 Teleport、Slots、Props、Emits)等。
🎯 设计目标
- 可复用:不同页面可以直接引入 Modal。
- 可扩展:支持自定义标题、内容和底部按钮。
- 可控制:父组件通过 v-model 或 props 来控制显隐。
- 可传送:使用 Teleport 挂载到
body,避免嵌套样式影响。
🧩 组件接口设计
// Modal.vue
defineProps<{
modelValue: boolean; // 是否显示
title?: string; // 模态框标题
width?: string; // 模态框宽度
}>();
defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'confirm'): void;
(e: 'cancel'): void;
}>();
使用 v-model 实现双向绑定,这样父组件只需控制一个 showModal 状态即可。
🧬 组件实现示例(Modal.vue)
这里是一个简洁版 Modal 实现参考:
<template>
<teleport to="body">
<div v-if="modelValue" class="modal-overlay" @click.self="closeModal">
<div class="modal-container" :style="{ width }">
<div class="modal-header">
<h3>{{ title }}</h3>
<button class="close-btn" @click="closeModal">×</button>
</div>
<div class="modal-body">
<slot />
</div>
<div class="modal-footer">
<slot name="footer">
<button @click="closeModal">取消</button>
<button @click="confirm">确定</button>
</slot>
</div>
</div>
</div>
</teleport>
</template>
<script setup lang="ts">
const props = defineProps<{
modelValue: boolean;
title?: string;
width?: string;
}>();
const emit = defineEmits(['update:modelValue', 'confirm', 'cancel']);
const closeModal = () => {
emit('update:modelValue', false);
emit('cancel');
};
const confirm = () => {
emit('confirm');
};
</script>
<style scoped>
.modal-overlay {
position: fixed;
top: 0; left: 0;
width: 100vw; height: 100vh;
background: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 999;
}
.modal-container {
background: white;
border-radius: 8px;
padding: 16px;
min-width: 320px;
}
.modal-header {
display: flex; justify-content: space-between;
align-items: center;
border-bottom: 1px solid #eee;
padding-bottom: 8px;
}
.modal-body {
padding: 16px 0;
}
.modal-footer {
text-align: right;
border-top: 1px solid #eee;
padding-top: 8px;
}
.close-btn {
background: none;
border: none;
cursor: pointer;
font-size: 18px;
}
</style>
🧑💻 使用示例
父组件中使用:
<script setup lang="ts">
import { ref } from 'vue';
import Modal from '@/components/Modal.vue';
const showModal = ref(false);
const onConfirm = () => {
console.log('confirmed');
showModal.value = false;
};
</script>
<template>
<button @click="showModal = true">打开Modal</button>
<Modal v-model="showModal" title="确认操作" @confirm="onConfirm">
这里是自定义内容
<template #footer>
<button @click="showModal = false">关闭</button>
<button @click="onConfirm">确定</button>
</template>
</Modal>
</template>
🎨 加强点
✅ 可以添加动画(如 vue-transitions 或手动使用 @vue/transition),
✅ 可以用 Escape 键关闭,
✅ 可以添加拖拽功能,
✅ 可以支持动态注册(如通过 ModalService 实现全局调用)。
🎯 总结
通过使用 teleport、v-model 双向绑定、slots 和 emits,Vue 3 中实现 Modal 组件既清晰又优雅,这也是推荐的标准模式。需要我帮你补充动画、测试、或移动端优化吗?欢迎告诉我! 🎉