vue3的Teleport

本文详细介绍了Vue3中的Teleport组件用法,包括如何将模态框组件的部分代码移动到DOM树的任意位置,保持组件逻辑的同时简化样式处理。同时探讨了Teleport与Vue组件结合使用的方法及在同一目标元素上使用多个Teleport的情况。

Teleport 可以将我们模板有些与模板有关联的逻辑代码(只是逻辑有关)移动到DOM 中 Vue app 之外的其他位置,

比如,模态框组件,模态框的逻辑存在于组件中,但是模态框的快速定位就很难通过 CSS 来解决,或者需要更改组件组合。

使用Teleport将模态框的一部分代码移动

// 父组件
<template>
  <div>
    父组件
    <child />
  </div>
</template>

<script>
import { defineComponent } from "vue";

import child from "./teleportChild.vue";
export default defineComponent({
  name: "",
  components: {
    child,
  },
});
</script>

<style scoped></style>


// 子组件 child
<template>
  <div>
    <button @click="isShow = true">点击我显示弹出框</button>
    <teleport to="body">
      <div v-show="isShow">
        我是弹出框
        <button @click="isShow = false">点我关闭弹出框</button>
      </div>
    </teleport>
  </div>
</template>

<script>
import { ref } from "vue";
export default {
  name: "teleportChild",
  setup() {
    const isShow = ref(false);
    return { isShow };
  },
};
</script>

<style scoped></style>

与 Vue components 一起使用

如果 包含 Vue 组件,则它仍将是 父组件的逻辑子组件:

const app = Vue.createApp({
  template: `
    <h1>Root instance</h1>
    <parent-component />
  `
})

app.component('parent-component', {
  template: `
    <h2>This is a parent component</h2>
    <teleport to="#endofbody">
      <child-component name="John" />
    </teleport>
  `
})

app.component('child-component', {
  props: ['name'],
  template: `
    <div>Hello, {{ name }}</div>
  `
})

在这种情况下,即使在不同的地方渲染 child-component,它仍将是 parent-component 的子级,并将从中接收 name prop。

这也意味着来自父组件的注入按预期工作,并且子组件将嵌套在 Vue Devtools 中的父组件之下,而不是放在实际内容移动到的位置

在同一目标上使用多个 teleport

<teleport to="#modals">
  <div>A</div>
</teleport>
<teleport to="#modals">
  <div>B</div>
</teleport>

<!-- 最终结果-->
<div id="modals">
  <div>A</div>
  <div>B</div>
</div>

多个 组件可以将其内容挂载到同一个目标元素。顺序将是一个简单的追加——稍后挂载将位于目标元素中较早的挂载之后。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值