vue3 中 点击按钮 弹出遮罩层的写法
时间: 2023-09-24 11:13:54 浏览: 257
在 Vue3 中,可以使用 Teleport(传送门)组件来实现弹出遮罩层的效果。具体步骤如下:
1. 在模板中添加 Teleport 组件,将弹出层内容放在 Teleport 组件内部,并指定目标容器。例如:
```html
<template>
<div>
<button @click="showModal = true">点击弹出层</button>
<teleport to="body">
<div v-if="showModal" class="modal">
<div class="modal-content">
<!-- 弹出层内容 -->
<h2>这是弹出层</h2>
<button @click="showModal = false">关闭</button>
</div>
</div>
</teleport>
</div>
</template>
```
2. 在 data 中定义一个变量(例如 showModal)来控制弹出层的显示和隐藏。初始值为 false。
```js
<script>
export default {
data() {
return {
showModal: false
}
}
}
</script>
```
3. 在样式中定义遮罩层的样式(例如 modal),并设置 z-index 属性使其位于页面最上层。例如:
```css
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background-color: white;
padding: 20px;
border-radius: 5px;
}
```
这样,当点击按钮时,弹出层就会显示在页面中央,并在页面最上层覆盖其他内容。
阅读全文
相关推荐















