vue3 Teleport组件

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>

显示结果如下:

image.png

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

以上就是vue3 Teleport组件的基本使用!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容