vue实现弹窗代码
基础弹窗实现
使用Vue的v-if或v-show控制弹窗显示隐藏:
<template>
<button @click="showModal = true">打开弹窗</button>
<div class="modal" v-if="showModal">
<div class="modal-content">
<span class="close" @click="showModal = false">×</span>
<p>弹窗内容</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showModal: 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;
width: 80%;
max-width: 500px;
}
.close {
float: right;
cursor: pointer;
}
</style>
组件化弹窗
创建可复用的弹窗组件:
<!-- Modal.vue -->
<template>
<transition name="fade">
<div class="modal" v-if="show">
<div class="modal-content">
<slot></slot>
</div>
</div>
</transition>
</template>
<script>
export default {
props: {
show: Boolean
}
}
</script>
父组件中使用:
<template>
<button @click="showModal = true">打开弹窗</button>
<Modal :show="showModal" @close="showModal = false">
<p>自定义弹窗内容</p>
</Modal>
</template>
使用第三方库
安装vue-js-modal库:
npm install vue-js-modal
全局注册:
import VModal from 'vue-js-modal'
Vue.use(VModal)
使用示例:
<template>
<button @click="show">打开弹窗</button>
<modal name="example" height="auto">
<p>弹窗内容</p>
<button @click="hide">关闭</button>
</modal>
</template>
<script>
export default {
methods: {
show() {
this.$modal.show('example')
},
hide() {
this.$modal.hide('example')
}
}
}
</script>
动态弹窗内容
通过props传递动态内容:
<Modal :title="modalTitle" :content="modalContent">
<template v-slot:footer>
<button @click="submit">提交</button>
</template>
</Modal>
动画效果
添加过渡动画:

.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}






