vue3 teleport 使用

242 阅读1分钟

teleport 顾名思义就是传送的意思,把包裹里面的dom元素移动到哪个dom的下面,如:移动到body下面

<template>

  <button @click="isFlag = true">点我显示弹窗</button>

  <teleport to='body' >

    <div class="mask" v-if="isFlag">

      <div class="content">

        <h2>我是内容</h2>

        <h2>我是内容</h2>

        <h2>我是内容</h2>

        <h2>我是内容</h2>

        <button @click="isFlag = false">点我关闭弹窗</button>

      </div>

    </div>

  </teleport>

</template>


<script setup>

import { ref, onMounted } from 'vue'


const isFlag = ref(false)

</script>


<style scoped>

.mask {

  background: rgba(0, 0, 0, 0.5);

  position: absolute;

  left: 0; right: 0; top: 0; bottom: 0;

  text-align: center;

}

.content {

  background-color: #fff;

  padding: 8px;

  position: absolute;

  left: 50%;

  top: 50%;

  transform: translate(-50%, -50%);

  width: 300px;


}

</style>

如图

图片.png

比如放到app下面

<teleport to='#app' >

    <div class="mask" v-if="isFlag">

      <div class="content">

        <h2>我是内容</h2>

        <h2>我是内容</h2>

        <h2>我是内容</h2>

        <h2>我是内容</h2>

        <button @click="isFlag = false">点我关闭弹窗</button>

      </div>

    </div>

  </teleport>

如图

图片.png