vue弹窗组件实现方法
基础弹窗组件实现
创建Modal.vue文件作为基础组件模板:
<template>
<div class="modal-mask" v-if="visible" @click.self="close">
<div class="modal-container">
<slot name="header">
<h3>{{ title }}</h3>
</slot>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<slot name="footer">
<button @click="close">关闭</button>
</slot>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
visible: Boolean,
title: String
},
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
<style>
.modal-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-container {
background: white;
padding: 20px;
border-radius: 4px;
min-width: 300px;
}
</style>
组件调用方式
在父组件中使用基础弹窗:
<template>
<button @click="showModal = true">打开弹窗</button>
<Modal v-model:visible="showModal" title="示例标题">
<p>这里是弹窗内容</p>
<template #footer>
<button @click="showModal = false">自定义按钮</button>
</template>
</Modal>
</template>
<script>
import Modal from './Modal.vue'
export default {
components: { Modal },
data() {
return {
showModal: false
}
}
}
</script>
高级功能扩展
支持动画效果的弹窗组件:
<template>
<transition name="modal">
<div class="modal-mask" v-if="visible" @click.self="close">
<div class="modal-container">
<!-- 原有内容 -->
</div>
</div>
</transition>
</template>
<style>
.modal-enter-active,
.modal-leave-active {
transition: opacity 0.3s ease;
}
.modal-enter-from,
.modal-leave-to {
opacity: 0;
}
</style>
全局弹窗服务
创建可编程调用的全局弹窗服务:
// modalService.js
import { createApp } from 'vue'
export default {
install(app) {
app.config.globalProperties.$modal = {
show(options) {
const modalApp = createApp({
data() {
return {
visible: true,
...options
}
},
template: `
<Modal v-model:visible="visible" :title="title">
{{ content }}
</Modal>
`
})
modalApp.component('Modal', Modal)
const el = document.createElement('div')
document.body.appendChild(el)
modalApp.mount(el)
}
}
}
}
在main.js中注册服务:
import modalService from './modalService'
app.use(modalService)
组件内调用方式:
this.$modal.show({
title: '提示',
content: '操作成功'
})






