vue3-teleport传送组件

100 阅读1分钟

定义

<Teleport> 是一个内置组件,它可以将一个组件内部的一部分模板“传送”到该组件的 DOM 结构外层的位置去。

父组件

<template>
  <div>
    <t-button @click="onClick">点我传送C组件</t-button>
    <div id="v1" style="background-color: red; height: 800px">A区域</div>
    <div id="v2" style="background-color: #1dc8e5; height: 800px">B区域</div>
    <teleport :to="choice">
      <c-vue />
    </teleport>
  </div>
</template>

<script lang="ts">
export default {
  name: 'ApplyAWSIndex',
};
</script>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import CVue from './C.vue';

const choice = ref('body');

const onClick = () => {
  choice.value = choice.value === '#v1' ? '#v2' : '#v1';
};

onMounted(() => {
  choice.value = '#v1';
});
</script>

<style scoped></style>

子组件

<template>
  <div style="border: 1px solid black; height: 500px; background-color: #3d87ff">我是C</div>
</template>

<script setup lang="ts"></script>

<style scoped></style>