vue 实现弹框
实现基础弹框组件
在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-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
}
.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>
使用第三方库实现弹框
对于更复杂的需求,可以使用现成的UI库:
-
Element UI:

<el-dialog :visible.sync="dialogVisible" title="提示"> <span>这是一段信息</span> <template #footer> <el-button @click="dialogVisible = false">取消</el-button> </template> </el-dialog> -
Vuetify:
<v-dialog v-model="dialog" max-width="500px"> <v-card> <v-card-title>标题</v-card-title> <v-card-text>内容</v-card-text> <v-card-actions> <v-btn @click="dialog = false">关闭</v-btn> </v-card-actions> </v-card> </v-dialog>
动画效果实现
为弹框添加过渡动画:

<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, .modal-leave-to {
opacity: 0;
}
</style>
全局弹框服务
创建可全局调用的弹框服务:
// modalService.js
import Vue from 'vue'
const ModalComponent = Vue.extend({
template: '<div class="modal">...</div>'
})
export default {
show(options) {
const instance = new ModalComponent({
propsData: options
})
instance.$mount()
document.body.appendChild(instance.$el)
return instance
}
}
在main.js中注册:
import modalService from './modalService'
Vue.prototype.$modal = modalService
组件中调用:
this.$modal.show({
title: '提示',
content: '操作成功'
})






