vue3写一个弹窗
时间: 2023-07-01 08:17:21 浏览: 54
好的,下面是一个简单的弹窗组件的代码示例:
```vue
<template>
<div v-if="show">
<div class="modal-wrapper">
<div class="modal">
<div class="modal-header">
<h3>{{ title }}</h3>
<button @click="close">X</button>
</div>
<div class="modal-body">
{{ message }}
</div>
<div class="modal-footer">
<button @click="close">关闭</button>
</div>
</div>
</div>
<div class="modal-overlay"></div>
</div>
</template>
<script>
export default {
props: {
show: {
type: Boolean,
required: true
},
title: {
type: String,
default: ""
},
message: {
type: String,
default: ""
}
},
methods: {
close() {
this.$emit("close");
}
}
};
</script>
<style scoped>
.modal-wrapper {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
}
.modal {
max-width: 600px;
margin: 0 auto;
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.modal-header h3 {
margin: 0;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9998;
}
</style>
```
使用时,可以在父组件中引入该组件,并通过 `v-show` 或 `v-if` 控制其显示或隐藏:
```vue
<template>
<div>
<button @click="showModal = true">点击打开弹窗</button>
<modal :show="showModal" title="提示" message="这是一个弹窗!" @close="showModal = false" />
</div>
</template>
<script>
import Modal from "./Modal.vue";
export default {
components: {
Modal
},
data() {
return {
showModal: false
};
}
};
</script>
```
以上代码实现了一个简单的弹窗,点击按钮后会显示弹窗,点击关闭按钮或弹窗外部的遮罩层可以关闭弹窗。