vue手动实现弹窗
实现弹窗的基本结构
在Vue中手动实现弹窗,需要创建一个可复用的弹窗组件。弹窗组件通常包含遮罩层、内容区域以及关闭按钮。
<template>
<div class="modal-mask" v-show="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>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
show: {
type: Boolean,
default: false
},
title: {
type: String,
default: '提示'
}
},
methods: {
close() {
this.$emit('update:show', 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;
border-radius: 4px;
width: 400px;
padding: 20px;
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.modal-header button {
background: none;
border: none;
font-size: 20px;
cursor: pointer;
}
.modal-footer {
margin-top: 20px;
text-align: right;
}
</style>
使用弹窗组件
在父组件中使用弹窗组件时,需要通过v-model控制弹窗的显示与隐藏。
<template>
<div>
<button @click="showModal = true">打开弹窗</button>
<modal-dialog v-model:show="showModal" title="自定义标题">
<p>这里是弹窗内容</p>
</modal-dialog>
</div>
</template>
<script>
import ModalDialog from './ModalDialog.vue';
export default {
components: {
ModalDialog
},
data() {
return {
showModal: false
};
}
};
</script>
添加动画效果
为弹窗添加过渡动画可以提升用户体验,使用Vue的transition组件实现淡入淡出效果。
<template>
<transition name="modal">
<div class="modal-mask" v-show="show" @click.self="close">
<!-- 其余代码保持不变 -->
</div>
</transition>
</template>
<style scoped>
.modal-enter-active,
.modal-leave-active {
transition: opacity 0.3s ease;
}
.modal-enter-from,
.modal-leave-to {
opacity: 0;
}
</style>
实现全局弹窗
通过Vue的插件机制实现全局弹窗,可以在任何组件中调用弹窗而无需单独引入。
// modalPlugin.js
import ModalDialog from './ModalDialog.vue';
export default {
install(app) {
app.component('ModalDialog', ModalDialog);
app.config.globalProperties.$modal = {
show(options) {
// 实现全局弹窗逻辑
}
};
}
};
处理弹窗内容动态渲染
对于需要动态渲染内容的弹窗,可以使用render函数或动态组件实现更灵活的配置。
<script>
export default {
props: {
component: {
type: [Object, Function],
default: null
},
props: {
type: Object,
default: () => ({})
}
},
render() {
return h(this.component, this.props);
}
};
</script>





