用vue写一个精美样式的模态框
时间: 2023-05-19 08:07:22 浏览: 129
当然可以!以下是一个简单的 Vue 模态框组件示例:
```html
<template>
<div class="modal" v-if="show">
<div class="modal-overlay" @click="close"></div>
<div class="modal-container">
<div class="modal-header">
<h3>{{ title }}</h3>
<button class="modal-close" @click="close">×</button>
</div>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<button class="modal-button" @click="close">{{ buttonText }}</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
show: Boolean,
title: String,
buttonText: {
type: String,
default: 'Close'
}
},
methods: {
close() {
this.$emit('close');
}
}
};
</script>
<style>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
display: flex;
justify-content: center;
align-items: center;
}
.modal-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-container {
position: relative;
width: 500px;
max-width: 100%;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
border-bottom: 1px solid #ccc;
}
.modal-header h3 {
margin: 0;
}
.modal-close {
border: none;
background-color: transparent;
font-size: 20px;
cursor: pointer;
}
.modal-body {
padding: 20px;
}
.modal-footer {
display: flex;
justify-content: flex-end;
align-items: center;
padding: 20px;
border-top: 1px solid #ccc;
}
.modal-button {
border: none;
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
</style>
```
你可以在父组件中使用这个模态框组件,例如:
```html
<template>
<div>
<button @click="showModal = true">Show Modal</button>
<modal :show="showModal" title="My Modal">
<p>This is my modal content.</p>
</modal>
</div>
</template>
<script>
import Modal from './Modal.vue';
export default {
components: {
Modal
},
data() {
return {
showModal: false
};
}
};
</script>
```
这个示例中,当用户点击 "Show Modal" 按钮时,模态框会显示出来,包含标题 "My Modal" 和内容 "This is my modal content."。用户可以点击模态框上的 "Close" 按钮或点击模态框外部的遮罩层来关闭模态框。