vue实现弹层
Vue 实现弹层的方法
使用 Vue 原生组件实现弹层
创建一个基础的弹层组件,利用 v-if 或 v-show 控制显示隐藏。
<template>
<div class="modal" v-if="isVisible">
<div class="modal-content">
<span class="close" @click="closeModal">×</span>
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
isVisible: {
type: Boolean,
default: false
}
},
methods: {
closeModal() {
this.$emit('close');
}
}
};
</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%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
</style>
使用第三方库(如 Element UI)
Element UI 提供了现成的弹层组件 el-dialog,可以快速实现弹层功能。
<template>
<el-button @click="dialogVisible = true">打开弹层</el-button>
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%">
<span>这是一段内容</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="dialogVisible = false">确定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
data() {
return {
dialogVisible: false
};
}
};
</script>
使用 Vue Teleport 实现弹层
Vue 3 的 Teleport 功能可以将弹层渲染到 DOM 树的任意位置,避免样式冲突。
<template>
<button @click="showModal = true">打开弹层</button>
<Teleport to="body">
<div v-if="showModal" class="modal">
<div class="modal-content">
<p>弹层内容</p>
<button @click="showModal = false">关闭</button>
</div>
</div>
</Teleport>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const showModal = ref(false);
return { showModal };
}
};
</script>
<style>
.modal {
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;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 5px;
}
</style>
动态控制弹层内容
通过插槽或动态组件实现弹层内容的灵活切换。
<template>
<button @click="openModal('contentA')">打开弹层A</button>
<button @click="openModal('contentB')">打开弹层B</button>
<Modal :isVisible="isVisible" @close="closeModal">
<component :is="currentComponent" />
</Modal>
</template>
<script>
import ContentA from './ContentA.vue';
import ContentB from './ContentB.vue';
export default {
components: { ContentA, ContentB },
data() {
return {
isVisible: false,
currentComponent: null
};
},
methods: {
openModal(component) {
this.currentComponent = component;
this.isVisible = true;
},
closeModal() {
this.isVisible = false;
}
}
};
</script>
弹层动画效果
通过 Vue 的过渡(Transition)组件为弹层添加动画效果。
<template>
<button @click="showModal = true">打开弹层</button>
<Transition name="fade">
<div v-if="showModal" class="modal">
<div class="modal-content">
<p>弹层内容</p>
<button @click="showModal = false">关闭</button>
</div>
</div>
</Transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>






