vue实现弹框组件
创建弹框组件
在Vue项目中创建一个弹框组件,通常命名为Modal.vue。组件包含基本的弹框结构,如标题、内容和操作按钮。
<template>
<div class="modal" v-if="isVisible">
<div class="modal-content">
<span class="close" @click="closeModal">×</span>
<h3>{{ title }}</h3>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<button @click="closeModal">取消</button>
<button @click="confirmModal">确认</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: '提示'
},
isVisible: {
type: Boolean,
default: false
}
},
methods: {
closeModal() {
this.$emit('close');
},
confirmModal() {
this.$emit('confirm');
}
}
};
</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;
z-index: 1000;
}
.modal-content {
background-color: white;
padding: 20px;
border-radius: 5px;
width: 80%;
max-width: 500px;
}
.close {
float: right;
cursor: pointer;
font-size: 24px;
}
.modal-footer {
margin-top: 20px;
text-align: right;
}
.modal-footer button {
margin-left: 10px;
}
</style>
使用弹框组件
在父组件中引入并使用弹框组件。通过v-model或自定义事件控制弹框的显示与隐藏。

<template>
<div>
<button @click="showModal = true">打开弹框</button>
<Modal
v-model="showModal"
title="自定义标题"
@close="showModal = false"
@confirm="handleConfirm"
>
<p>这里是弹框的内容</p>
</Modal>
</div>
</template>
<script>
import Modal from './Modal.vue';
export default {
components: {
Modal
},
data() {
return {
showModal: false
};
},
methods: {
handleConfirm() {
alert('确认操作');
this.showModal = false;
}
}
};
</script>
通过事件控制弹框
弹框组件通过$emit触发事件,父组件监听这些事件并执行相应的逻辑。
<Modal
:isVisible="showModal"
@close="handleClose"
@confirm="handleConfirm"
/>
动态插槽内容
弹框组件支持插槽,可以在父组件中动态插入内容,增强灵活性。

<Modal v-model="showModal">
<template #default>
<p>动态内容</p>
<input type="text" v-model="inputValue" />
</template>
</Modal>
全局注册弹框组件
如果需要频繁使用弹框,可以将其全局注册,避免重复引入。
// main.js
import Vue from 'vue';
import Modal from './components/Modal.vue';
Vue.component('Modal', Modal);
动画效果
为弹框添加动画效果,提升用户体验。使用Vue的过渡组件实现淡入淡出效果。
<template>
<transition name="fade">
<div class="modal" v-if="isVisible">
<!-- 弹框内容 -->
</div>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>






