vue实现对话框效果
Vue 对话框实现方法
使用 Vue 原生组件
创建一个对话框组件 Dialog.vue:
<template>
<div class="dialog" v-if="visible">
<div class="dialog-content">
<slot></slot>
<button @click="close">关闭</button>
</div>
</div>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
<style>
.dialog {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
}
.dialog-content {
background: white;
padding: 20px;
border-radius: 5px;
}
</style>
在父组件中使用:
<template>
<button @click="showDialog = true">打开对话框</button>
<Dialog :visible.sync="showDialog">
<h3>对话框标题</h3>
<p>对话框内容...</p>
</Dialog>
</template>
<script>
import Dialog from './Dialog.vue'
export default {
components: { Dialog },
data() {
return {
showDialog: false
}
}
}
</script>
使用第三方库
安装 Element UI:
npm install element-ui
在 main.js 中引入:
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
使用 Element UI 的对话框:
<template>
<div>
<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>
</div>
</template>
<script>
export default {
data() {
return {
dialogVisible: false
}
}
}
</script>
使用 Teleport(Vue 3)
Vue 3 提供了 Teleport 组件,可以更方便地实现对话框:
<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: 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>
<Transition name="fade">
<div class="dialog" v-if="visible">
<!-- 对话框内容 -->
</div>
</Transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>






