vue实现弹框组件
Vue 弹框组件实现方法
基础弹框组件结构
创建一个名为Modal.vue的文件,包含以下基础结构:
<template>
<div class="modal-mask" v-show="visible" @click.self="close">
<div class="modal-container">
<div class="modal-header">
<slot name="header"></slot>
</div>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
<style scoped>
.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">
<template #header>
<h3>标题</h3>
</template>
<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-show="visible" @click.self="close">
<!-- 内容保持不变 -->
</div>
</transition>
</template>
<style scoped>
.modal-enter-active,
.modal-leave-active {
transition: opacity 0.3s ease;
}
.modal-enter-from,
.modal-leave-to {
opacity: 0;
}
.modal-container {
transition: transform 0.3s ease;
}
.modal-enter-active .modal-container,
.modal-leave-active .modal-container {
transform: scale(1);
}
.modal-enter-from .modal-container,
.modal-leave-to .modal-container {
transform: scale(0.9);
}
</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">
<template #header>
<h3>{{ title }}</h3>
</template>
<div v-html="content"></div>
<template #footer>
<button @click="visible = false">关闭</button>
</template>
</Modal>
`
})
modalApp.component('Modal', Modal)
const mountNode = document.createElement('div')
document.body.appendChild(mountNode)
modalApp.mount(mountNode)
}
}
}
}
在main.js中注册服务:
import modalService from './modalService.js'
const app = createApp(App)
app.use(modalService)
app.mount('#app')
使用方法:
this.$modal.show({
title: '提示',
content: '操作成功'
})






