Vue3 Teleport
2020-11-26 10:56
676 查看
为什么需要 Teleport?
以 Dialog 组件为例,通常需要在一个组件中引入 Dialog 组件。然而,有时一部分逻辑属于 Dialog 所在的组件中,从技术角度来看,最好将这一部分移动到根节点之外的位置。
另外一个问题, 当 Dialog 组件使用
position: absolute相对于它所在的组件进行绝对定位时,样式变得十分混乱。
使用 Teleport
teleport 意为传送,它提供了一种干净的方法,允许我们控制在 DOM 中哪个父节点下呈现 HTML。
Step1: 创建传送的目标节点,此处为 index.html 中的和根节点同级的 id 为 model 的节点。
... <div id="app"></div> <div id="model"></div> ...
Step2: 使用
<teleport>将需要被传送的组件包裹起来, 此处将 Dialog 包裹。
<template> <teleport> <div>I'am a Dialog.</div> </teleport> </template>
Step3:指定 telport 的
to属性,告诉它要传送到 id 为 model 的节点。
<template> <teleport to="#modal"> <div>I'am a Dialog.</div> </teleport> </template>
接下来无论在哪个组件中使用该 Dialog 组件,都会将它渲染到 id 为 model 的节点下。这就实现了传送的功能。
Component.vue
<template> <div> <Dialog></Dialog> </div> </template> <script> import Dialog from "./components/Dialog.vue"; export default { components: { Dialog }, } </script>
值得注意的是,即使在不同的地方渲染 Dialog,它仍将是 Component.vue 的子级,并将从中接收 props。还可以将多个 teleport 挂在到同一个目标节点上,挂载的顺序是从前到后,即先挂载的位于前面。
相关文章推荐
- iTeleport:让Siri可以跨平台运行OS X应用
- lightoj1380 Teleport
- Teleport Pro使用教程
- vue3.x创建项目
- vue适配不同电脑分辨率(vue3.x)
- 使用vite搭建Vue3项目
- iTeleport:让Siri可以跨平台运行OS X应用
- teleport使用说明
- [转]Teleport Ultra/Teleport Pro的冗余代码批量清理方法
- Python3.6+Django2.2+Vue3搭建前后端分离的自动化测试管理平台
- 最全Vue知识点(基础到进阶,覆盖vue3)
- Vue3 为何使用 Proxy 实现数据监听
- Teleport Ultra 垃圾代码 tppabs的清理
- Teleport Ultra/Teleport Pro的冗余代码批量清理方法
- 【推荐】开源堡垒机Teleport
- Vue3 中的数据侦测的实现
- Vue3 尝鲜 Hook + TypeScript 取代 Vuex 实现图书管理小型应用
- Vue3教程:用 Vue3 开发小程序,这里有一份实际的代码案例!
- Teleport - the Unix/Linux cd command, improved
- TELEPORTSTONE.LUA --传送宝石