vue 实现弹窗
使用 Vue 实现弹窗
基础弹窗组件实现
创建一个基础的弹窗组件 Modal.vue:
<template>
<div class="modal" v-if="visible">
<div class="modal-content">
<span class="close" @click="close">×</span>
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
<style>
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 500px;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
</style>
在父组件中使用弹窗
在父组件中引入并使用弹窗:
<template>
<div>
<button @click="showModal = true">打开弹窗</button>
<Modal :visible.sync="showModal">
<h3>弹窗标题</h3>
<p>这是弹窗内容...</p>
</Modal>
</div>
</template>
<script>
import Modal from './Modal.vue'
export default {
components: { Modal },
data() {
return {
showModal: false
}
}
}
</script>
高级弹窗功能扩展
为弹窗添加动画效果:
<template>
<transition name="fade">
<div class="modal" v-if="visible">
<div class="modal-content">
<span class="close" @click="close">×</span>
<slot></slot>
</div>
</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
全局弹窗服务
创建全局弹窗服务:
// modalService.js
import Vue from 'vue'
const ModalConstructor = Vue.extend(require('./Modal.vue').default)
const ModalService = {
open(options) {
const instance = new ModalConstructor({
propsData: options.props
})
instance.$slots.default = [options.content]
instance.$mount()
document.body.appendChild(instance.$el)
return {
close: () => {
instance.$el.remove()
instance.$destroy()
}
}
}
}
export default ModalService
使用全局弹窗服务:
import ModalService from './modalService'
ModalService.open({
props: {
visible: true
},
content: '这是全局弹窗内容'
})
第三方弹窗库推荐
对于更复杂的需求,可以考虑以下第三方库:
vue-js-modal: 功能丰富,支持多种模态框类型v-modal: 轻量级解决方案element-ui或ant-design-vue的弹窗组件







