vue3 Teleport组件
2020-11-15 本文已影响0人
深度剖析JavaScript
Teleport
,被称为传送门组件,用于提供一种简洁的方式,指定其里面内容的父元素
例如,定义一个模态框,该模态框原本是在一个组件中的,但我希望当弹出的时候,它的结构是body
下,与#app
平级。如下代码
<template>
<button @click="modalsOpen = true">弹出框按钮</button>
<teleport to='body'>
<div v-if="modalsOpen" class="modals">
<div>
<p>这是一个弹出框,并且是被传送到body上</p>
<button @click="modalsOpen = false">关闭</button>
</div>
</div>
</teleport>
</template>
<script>
import { ref } from "vue";
export default {
name: "Modals",
setup() {
let modalsOpen = ref(false);
return { modalsOpen };
},
};
</script>
<style scoped>
.modals{
background-color: rgba(0, 0, 0, .5);
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.modals div{
border-radius: 4px;
width: 300px;
height: 100px;
background-color:#fff;
padding: 20px;
display: flex;
flex-direction: column;
justify-content: center;
font-size: .9em;
color: rgba(0, 0, 0, .9);
}
button{
padding: 5px;
}
</style>
显示结果如下:

我们发现,
teleport
组件使用也比较简单,就是通过to
属性能将其里面的内容被传送到指定的哪个元素下,属性值为元素选择器
以上就是vue3 Teleport
组件的基本使用!