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>
相关推荐
weixin_427771611 天前
css font-size 的妙用
前端·css
凤凰战士芭比Q1 天前
web中间件——Nginx
前端·nginx·中间件
一 乐1 天前
点餐|智能点餐系统|基于java+ Springboot的动端的点餐系统小程序(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·小程序·论文
bitbitDown1 天前
从零打造一个 Vite 脚手架工具:比你想象的简单多了
前端·javascript·面试
liangshanbo12151 天前
CSS 数学函数完全指南:从基础计算到高级动画
前端·css
码上成长1 天前
GraphQL:让前端自己决定要什么数据
前端·后端·graphql
冴羽1 天前
为什么在 JavaScript 中 NaN !== NaN?背后藏着 40 年的技术故事
前端·javascript·node.js
久爱@勿忘1 天前
vue下载项目内静态文件
前端·javascript·vue.js
前端炒粉1 天前
21.搜索二维矩阵 II
前端·javascript·算法·矩阵
合作小小程序员小小店1 天前
web网页开发,在线%台球俱乐部管理%系统,基于Idea,html,css,jQuery,jsp,java,ssm,mysql。
java·前端·jdk·intellij-idea·jquery·web