06. teleport标签

2022-11-16 14:01:23发布
47

teleport的作用是修改dom元素的层级


例子

index.vue

<template>
  <div class="parent">
    <Dialog />
  </div>
</template>
<script setup>
import Dialog from "./dialog.vue";
</script>

dialog.vue

<template>
  <div class="child">
    <div class="dialog">dialog</div>
  </div>
</template>
<style scoped>
.dialog {
  width: 500px;
  height: 200px;
  background: #fff;
  border: 1px solid #000;
}
</style>

运行效果

注意类名为“dialog”的div,它是在child的里面的。现在加上 teleport标签


dialog.vue

<template>
  <div class="child">
    <teleport to="body">
      <div class="dialog">dialog</div>
    </teleport>
  </div>
</template>
<style scoped>
.dialog {
  width: 500px;
  height: 200px;
  background: #fff;
  border: 1px solid #000;
}
</style>

运行效果

teleport后面的to的值可以是html、head、body等。比如我可以这样写 :

<template>
  <div class="child">
    <teleport to="html">
      <div class="dialog">dialog</div>
    </teleport>
  </div>
</template>

运行效果 :