vue实现对话框效果
使用 Vue 实现对话框效果
对话框组件基础实现
创建对话框组件 Dialog.vue,包含模板、样式和逻辑:
<template>
<div class="dialog-overlay" v-if="visible" @click.self="close">
<div class="dialog-content">
<slot name="header">
<h3>{{ title }}</h3>
</slot>
<slot></slot>
<div class="dialog-footer">
<button @click="close">取消</button>
<button @click="confirm">确认</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
visible: Boolean,
title: {
type: String,
default: '提示'
}
},
methods: {
close() {
this.$emit('update:visible', false)
},
confirm() {
this.$emit('confirm')
this.close()
}
}
}
</script>
<style scoped>
.dialog-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.dialog-content {
background: white;
padding: 20px;
border-radius: 4px;
min-width: 300px;
}
.dialog-footer {
margin-top: 20px;
text-align: right;
}
</style>
在父组件中使用对话框
<template>
<div>
<button @click="showDialog = true">打开对话框</button>
<Dialog
v-model:visible="showDialog"
title="自定义标题"
@confirm="handleConfirm"
>
<p>这是对话框的内容</p>
</Dialog>
</div>
</template>
<script>
import Dialog from './Dialog.vue'
export default {
components: { Dialog },
data() {
return {
showDialog: false
}
},
methods: {
handleConfirm() {
console.log('确认操作')
}
}
}
</script>
使用 Vue Teleport 优化对话框
Vue 3 中可以使用 Teleport 将对话框渲染到 body 下,避免样式问题:
<template>
<Teleport to="body">
<div class="dialog-overlay" v-if="visible" @click.self="close">
<!-- 其余代码保持不变 -->
</div>
</Teleport>
</template>
添加动画效果
为对话框添加淡入淡出和缩放动画:
<template>
<Teleport to="body">
<Transition name="dialog">
<div class="dialog-overlay" v-if="visible" @click.self="close">
<div class="dialog-content">
<!-- 内容保持不变 -->
</div>
</div>
</Transition>
</Teleport>
</template>
<style scoped>
.dialog-enter-active,
.dialog-leave-active {
transition: opacity 0.3s ease;
}
.dialog-enter-from,
.dialog-leave-to {
opacity: 0;
}
.dialog-enter-active .dialog-content,
.dialog-leave-active .dialog-content {
transition: transform 0.3s ease;
}
.dialog-enter-from .dialog-content,
.dialog-leave-to .dialog-content {
transform: scale(0.9);
}
</style>
使用 Composition API 重构
Vue 3 的 Composition API 版本:
<script setup>
import { defineProps, defineEmits } from 'vue'
const props = defineProps({
visible: Boolean,
title: {
type: String,
default: '提示'
}
})
const emits = defineEmits(['update:visible', 'confirm'])
const close = () => {
emits('update:visible', false)
}
const confirm = () => {
emits('confirm')
close()
}
</script>
对话框扩展功能
-
自定义按钮文本:
<Dialog cancelText="关闭" confirmText="确定" /> -
禁用确认按钮:
<Dialog :confirmDisabled="true" /> -
异步操作:

methods: { async handleConfirm() { try { await someAsyncOperation() this.showDialog = false } catch (error) { console.error(error) } } }






