封装一个弹出框
时间: 2023-07-25 19:23:12 浏览: 56
好的,以下是一个简单的弹出框组件的示例:
```vue
<template>
<div v-if="visible" class="modal">
<div class="modal-mask" @click="close"></div>
<div class="modal-container">
<div class="modal-header">
<h2>{{ title }}</h2>
<button class="modal-close" @click="close">×</button>
</div>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<button class="modal-cancel" @click="close">{{ cancelText }}</button>
<button class="modal-confirm" @click="confirm">{{ confirmText }}</button>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Modal",
props: {
visible: {
type: Boolean,
default: false,
},
title: {
type: String,
default: "Modal Title",
},
cancelText: {
type: String,
default: "Cancel",
},
confirmText: {
type: String,
default: "OK",
},
},
methods: {
close() {
this.$emit("update:visible", false);
this.$emit("close");
},
confirm() {
this.$emit("confirm");
this.close();
},
},
};
</script>
<style>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
}
.modal-mask {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-container {
position: relative;
background-color: #f5f5f5;
width: 400px;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.modal-close {
border: none;
background-color: transparent;
font-size: 24px;
cursor: pointer;
}
.modal-body {
margin-bottom: 20px;
}
.modal-footer {
display: flex;
justify-content: flex-end;
}
.modal-cancel,
.modal-confirm {
border: none;
background-color: #0078e7;
color: #fff;
padding: 10px 20px;
margin-left: 10px;
border-radius: 5px;
cursor: pointer;
}
.modal-confirm:hover {
background-color: #005ca9;
}
</style>
```
这个组件封装了一个基本的弹出框,包括标题、内容和两个按钮(确认和取消)。它使用了插槽来允许用户在弹出框中添加自定义内容。用户可以通过 `visible` 属性来控制弹出框的显示或隐藏。当用户点击关闭按钮或取消按钮时,弹出框会关闭并触发一个 `close` 事件。当用户点击确认按钮时,弹出框会触发一个 `confirm` 事件。
你可以在使用该组件时,通过传递不同的属性来自定义弹出框的行为和样式。例如:
```vue
<template>
<div>
<button @click="showModal = true">Show Modal</button>
<modal :visible.sync="showModal" title="My Modal" confirmText="OK">
<p>Are you sure you want to perform this action?</p>
</modal>
</div>
</template>
<script>
import Modal from "./Modal.vue";
export default {
name: "App",
components: {
Modal,
},
data() {
return {
showModal: false,
};
},
};
</script>
```
在这个例子中,我们传递了 `title` 和 `confirmText` 属性来自定义弹出框的标题和确认按钮的文本。我们还使用了 `.sync` 修饰符来实现双向绑定 `visible` 属性,这样当用户关闭弹出框时,`showModal` 变量会自动更新。