用vue实现弹窗
使用Vue实现弹窗
基础弹窗组件实现
创建一个名为Modal.vue的组件文件,包含模板、样式和逻辑:
<template>
<div class="modal-mask" v-if="show" @click.self="close">
<div class="modal-container">
<div class="modal-header">
<h3>{{ title }}</h3>
<button @click="close">×</button>
</div>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<button @click="close">关闭</button>
<button @click="confirm" v-if="showConfirm">确认</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
show: Boolean,
title: String,
showConfirm: {
type: Boolean,
default: true
}
},
methods: {
close() {
this.$emit('update:show', false);
},
confirm() {
this.$emit('confirm');
}
}
};
</script>
<style>
.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;
border-radius: 8px;
min-width: 300px;
max-width: 80%;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
}
.modal-header {
display: flex;
justify-content: space-between;
padding: 15px;
border-bottom: 1px solid #eee;
}
.modal-body {
padding: 15px;
}
.modal-footer {
padding: 15px;
text-align: right;
border-top: 1px solid #eee;
}
</style>
在父组件中使用弹窗
在需要弹窗的父组件中引入并使用:
<template>
<div>
<button @click="showModal = true">打开弹窗</button>
<Modal
v-model:show="showModal"
title="示例弹窗"
@confirm="handleConfirm"
>
<p>这里是弹窗内容</p>
</Modal>
</div>
</template>
<script>
import Modal from './Modal.vue';
export default {
components: { Modal },
data() {
return {
showModal: false
};
},
methods: {
handleConfirm() {
console.log('确认按钮被点击');
this.showModal = false;
}
}
};
</script>
使用Vue插件方式全局注册
如需全局使用弹窗,可以创建插件:
// modalPlugin.js
import Modal from './Modal.vue';
export default {
install(app) {
app.component('Modal', Modal);
}
};
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import modalPlugin from './modalPlugin';
const app = createApp(App);
app.use(modalPlugin);
app.mount('#app');
动态控制弹窗内容
通过插槽和props实现内容动态化:
<Modal
v-model:show="showModal"
:title="modalTitle"
:show-confirm="hasConfirm"
>
<template v-slot:default>
<p>{{ modalContent }}</p>
<input v-model="inputValue" />
</template>
<template v-slot:footer>
<button @click="customAction">自定义按钮</button>
</template>
</Modal>
动画效果实现
为弹窗添加过渡动画:

<template>
<transition name="modal">
<div class="modal-mask" v-if="show" @click.self="close">
<!-- 弹窗内容 -->
</div>
</transition>
</template>
<style>
.modal-enter-active,
.modal-leave-active {
transition: opacity 0.3s ease;
}
.modal-enter-from,
.modal-leave-to {
opacity: 0;
}
.modal-enter-active .modal-container,
.modal-leave-active .modal-container {
transition: transform 0.3s ease;
}
.modal-enter-from .modal-container,
.modal-leave-to .modal-container {
transform: scale(0.9);
}
</style>






