Vue3 的“空投”Teleport的使用

前言:Teleport是一个内置的组件,可以将一个组件内部的一部分"传送"到该组件的DOM结构外层的位置去

使用场景:

  1. 全屏模态框
  2. 在已经布局好的页面上,进入到特定页面,需要在布局组件上渲染特定的内容
  3. 预览模式下,将内容展示在页面不同的地方

以上就是我在项目中使用的场景,更详细可前往官网查看

会遇到什么问题呢?

js 复制代码
[Vue warn]: Failed to locate Teleport target with selector "#teleport-header-left". Note the target element must exist before the component is mounted - i.e. the target cannot be rendered by the component itself, and ideally should be outside of the entire Vue component tree. 
js 复制代码
[Vue warn]: Invalid Teleport target on mount: null (object) 

大概就是需要空投的节点'#teleport-header-left',还没渲染,或不存在,Teleport就已经开始投送了。

解决的办法:

引入defineAsyncComponent,将含有Teleport的文件懒加载。

js 复制代码
import { defineAsyncComponent } from "vue";

const TeleportCom = definAsyncComponent(() => import('....'));

同一个组件内由上到下渲染,只要to的目标渲染了,就可以挂到对应的节点上。

还可以结合v-bind进行动态渲染到某个节点上去

js 复制代码
<Teleport :to="targetRef">
    <div>把我挂载<div>
</Teleport>

//js
const props = defineProps({
    targetRef: {
        type: String,
        default: 'body',
    }
})

禁用Teleport,场景:客户端需要空投,移动端不需要。

js 复制代码
<Teleport :disabled="isMobile">
  ...
</Teleport>

多个Teleport共享目标,挂载到同一个id上,那么会有先后顺序,也就是追加在后面渲染

js 复制代码
<Teleport to="#modals">
  <div>A</div>
</Teleport>
<Teleport to="#modals">
  <div>B</div>
</Teleport>
相关推荐
_瑞2 分钟前
深入理解 iOS 渲染原理
前端·ios
IT_陈寒5 分钟前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端
iCOD3R43 分钟前
Skill - kill-ai-slop 解决“AI 味”样式
前端·css·ai编程
皮音1 小时前
Skill 在项目中的实践 —— 从 Agent 困境到 Skill 工程化
前端
大龄秃头程序员1 小时前
RN 0.86 新架构实战:TurboModule + Fabric 组件 + iOS 原生容器,完整代码开源
前端·react native
这是个栗子1 小时前
前端开发中的常用工具函数(八)
开发语言·前端·javascript
Hilaku1 小时前
Vue 和 React 真正的差距,不在语法,而在团队犯错成本
前端·javascript·程序员
研☆香2 小时前
为什么变量声明在赋值前也能使用?—— 深入理解 JavaScript 变量提升与作用域
开发语言·前端·javascript
Liora_Yvonne2 小时前
目录结构到底怎么设计?别再把 components 和 utils 当垃圾桶了
前端
柯克七七2 小时前
我把 bug 修得太干净了,测试组以为这个模块本来就没问题
前端·javascript·typescript