vue弹出对话框
时间: 2023-06-30 21:25:49 浏览: 161
要在 Vue 中实现弹出对话框,可以使用第三方组件库如 Element UI 或者自定义组件。以下是一个简单的自定义组件示例:
1. 在 Vue 组件中定义弹出对话框组件:
```vue
<template>
<div class="dialog-wrapper" v-show="visible">
<div class="dialog">
<div class="dialog-header">
<h3>{{ title }}</h3>
<button @click="close">X</button>
</div>
<div class="dialog-body">
<slot></slot>
</div>
<div class="dialog-footer">
<button @click="confirm">确定</button>
<button @click="cancel">取消</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: "对话框"
},
visible: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit("update:visible", false);
},
confirm() {
this.$emit("confirm");
},
cancel() {
this.$emit("cancel");
}
}
};
</script>
<style scoped>
.dialog-wrapper {
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;
}
.dialog {
width: 400px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
.dialog-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border-bottom: 1px solid #eee;
}
.dialog-body {
padding: 10px;
}
.dialog-footer {
display: flex;
justify-content: flex-end;
align-items: center;
padding: 10px;
border-top: 1px solid #eee;
}
</style>
```
2. 在父组件中使用弹出对话框组件:
```vue
<template>
<div>
<button @click="showDialog">打开对话框</button>
<dialog v-model="dialogVisible" @confirm="handleConfirm" @cancel="handleCancel">
<p>这是一个对话框!</p>
</dialog>
</div>
</template>
<script>
import Dialog from "@/components/Dialog";
export default {
components: {
Dialog
},
data() {
return {
dialogVisible: false
};
},
methods: {
showDialog() {
this.dialogVisible = true;
},
handleConfirm() {
alert("你点击了确定按钮!");
this.dialogVisible = false;
},
handleCancel() {
alert("你点击了取消按钮!");
this.dialogVisible = false;
}
}
};
</script>
```
在这个示例中,我们定义了一个名为 `Dialog` 的组件,它包含一个标题、内容和两个按钮(确定和取消)。在父组件中,我们使用 `v-model` 指令来双向绑定弹出对话框的可见性。当用户点击确定或取消按钮时,会触发 `confirm` 或 `cancel` 事件,父组件可以通过监听这些事件来处理用户的操作。