<template>
<div>
<button @click="show">点我弹个窗</button>
<teleport to="body">
<!-- to后面的地址还可以是 html 或者其他 div等 -->
<!-- 表示将teleport包裹的这个div,移动到html这个结构中 -->
<div class="mask" v-if="isShow.showDialog">
<div class="dialog1">
<h2>这是个弹窗</h2>
<h4>
这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容这是内容
</h4>
<button class="dialog-btn" @click="hidden">关闭弹窗</button>
</div>
</div>
</teleport>
</div>
</template>
<script>
import { reactive } from "vue";
export default {
name: "dialog",
setup() {
let isShow = reactive({
showDialog: false,
});
function show() {
isShow.showDialog = true;
}
function hidden() {
isShow.showDialog = false;
}
return {
isShow,
show,
hidden,
};
},
};
</script>
<style >
.mask{
/* 创建遮罩层 */
position: absolute;
background: rgba(0, 0, 0, 0.5);
top: 0;
bottom: 0;
right: 0;
left: 0;
}
.dialog1 {
text-align: center;
width: 300px;
height: 200px;
background: green;
position: absolute;
top: 50%;
left: 50%;
/* top和left这个两个50%表示的是,这个弹框的顶部到页面的顶部,弹框的左侧到页面的左侧 */
transform: translate(-50%,-50%);
/* 这个偏移表示的是,偏移这个div框自身宽度和高度的50% */
}
</style>
效果如下: