vue中超简单的方法实现点击一个按钮出现弹框,点击弹框外关闭弹框
时间: 2023-12-05 21:06:04 浏览: 37
可以使用Vue.js的v-if指令来实现点击按钮弹出弹框的功能,再结合@click事件和@click.self事件来实现点击弹框外关闭弹框的功能。
具体代码如下:
```html
<template>
<div>
<button @click="showModal = true">打开弹框</button>
<div class="modal-mask" v-if="showModal" @click.self="showModal = false">
<div class="modal-wrapper">
<div class="modal-container">
<!-- 弹框内容 -->
<h3>这是一个弹框</h3>
<p>点击弹框外部即可关闭弹框</p>
<button @click="showModal = false">关闭弹框</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showModal: false
};
}
};
</script>
<style>
/* 弹框样式 */
.modal-mask {
position: fixed;
top: 0;
left: 0;
z-index: 9998;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: table;
transition: opacity 0.3s ease;
}
.modal-wrapper {
display: table-cell;
vertical-align: middle;
}
.modal-container {
width: 300px;
margin: 0px auto;
padding: 20px 30px;
background-color: #fff;
border-radius: 2px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.33);
transition: all 0.3s ease;
font-size: 14px;
text-align: center;
}
.modal-enter {
opacity: 0;
}
.modal-leave-active {
opacity: 0;
}
.modal-enter .modal-container,
.modal-leave-active .modal-container {
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
</style>
```
这里使用了一个`showModal`变量来控制弹框的显示与隐藏。当点击打开弹框按钮时,将`showModal`设置为`true`,此时弹框会显示出来。当点击弹框外时,会触发`@click.self`事件,此时将`showModal`设置为`false`,弹框会隐藏起来。在弹框内部的关闭按钮上,也需要触发将`showModal`设置为`false`的操作,以便关闭弹框。
另外,为了让弹框呈现居中显示的效果,还需要添加一些样式。