vue实现对话框效果
Vue 对话框实现方法
使用 Vue 原生语法
通过 v-if 或 v-show 控制对话框显示,结合 CSS 过渡动画:
<template>
<button @click="showDialog = true">打开对话框</button>
<div class="dialog-mask" v-if="showDialog" @click.self="closeDialog">
<div class="dialog-content">
<h3>标题</h3>
<p>对话框内容</p>
<button @click="closeDialog">关闭</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showDialog: false
}
},
methods: {
closeDialog() {
this.showDialog = false
}
}
}
</script>
<style>
.dialog-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
}
.dialog-content {
background: white;
padding: 20px;
border-radius: 4px;
min-width: 300px;
}
</style>
使用第三方组件库
Element UI 对话框示例:
<template>
<el-button @click="dialogVisible = true">打开对话框</el-button>
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%">
<span>这是一段内容</span>
<span slot="footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="dialogVisible = false">确定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
data() {
return {
dialogVisible: false
}
}
}
</script>
Vue 3 Composition API 实现
<template>
<button @click="openDialog">打开对话框</button>
<Teleport to="body">
<div v-if="isOpen" class="dialog">
<div class="dialog-content">
<slot></slot>
<button @click="closeDialog">关闭</button>
</div>
</div>
</Teleport>
</template>
<script setup>
import { ref } from 'vue'
const isOpen = ref(false)
const openDialog = () => {
isOpen.value = true
}
const closeDialog = () => {
isOpen.value = false
}
</script>
动态组件方式
创建可复用的对话框组件:
// Dialog.vue
export default {
props: {
show: Boolean,
title: String
},
emits: ['close'],
setup(props, { emit }) {
const close = () => {
emit('close')
}
return { close }
}
}
使用 Vuex 管理对话框状态
适合大型应用中的状态管理:
// store.js
export default new Vuex.Store({
state: {
dialog: {
show: false,
content: ''
}
},
mutations: {
showDialog(state, content) {
state.dialog.show = true
state.dialog.content = content
},
hideDialog(state) {
state.dialog.show = false
}
}
})






