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>
相关推荐
西瓜太郎123415 分钟前
Claude Code、Codex CLI、Gemini CLI 能否共用一枚 Key?先看协议选择矩阵
前端·api 网关·claude code·gemini cli·codex cli
陈随易2 小时前
在Finch用了62亿词元,我认为这是新一代Agent工具之神
前端·人工智能·后端
水域安全老周3 小时前
水趣钓鱼救生衣专利拆解:两级锁紧如何解决落水人衣分离
java·前端·网络
计算机魔术师3 小时前
Anthropic CEO突然喊踩刹车,OpenAI罕见力挺:AI这辆车不能只踩油门了
前端
wing983 小时前
从codex转战workbuddy使用一周的感受
前端·人工智能·后端
EatFan4 小时前
Java接入支付宝 JSAPI 支付保姆教程(二):流程讲解与前后端代码讲解
前端·spring boot·后端·微信小程序·小程序·uni-app
梦想平凡4 小时前
百游棋牌源代码开发搭建教程(五):房间创建、座位分配与请求幂等实现
前端·javascript·数据库·源代码管理
IT_陈寒4 小时前
Redis的Set操作居然能把我的服务整挂了?
前端·人工智能·后端
计算机魔术师5 小时前
Suno 发布 v6 音乐模型,推出 v6、v6-wild、v6-mini 三个版本
前端
whyweplay5 小时前
elpis : DSL动态组件学习
前端