认识teleport内置组件
在组件化开发中,我们封装一个组件A,在另外一个组件B中使用:
- 那么组件A中template的元素,会被挂载到组件B中template的某个位置;
- 最终我们的应用程序会形成一颗DOM树结构;
但是某些情况下,我们希望组件不是挂载在这个组件树上的,可能是移动到Vue app之外的其他位置: + 比如移动到body元素上,或者我们有其他的div#app之外的元素上;
- 这个时候我们就可以通过teleport来完成;
Teleport是什么呢?
- 它是一个Vue提供的内置组件,类似于react的Portals;
- teleport翻译过来是心灵传输、远距离运输的意思;
它有两个属性:
-
to:指定将其中的内容移动到的目标元素,可以使用选择器; -
disabled:是否禁用 teleport 的功能;
-
public/index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- teleport目标位置 -->
<div id="why"></div>
<!-- built files will be auto injected -->
</body>
</html>
App.vue
<template>
<div>
<teleport to="#why">
<h1>今天天气不错</h1>
<!--如果teleport内部有组件,组件的内容也会一同挂载到目标DOM内部-->
<hello-world />
</teleport>
<!--如果使用过个teleport挂载到同一目标Dom内,会一次按照属性进行挂载-->
<teleport to="#why">
<button>按钮</button>
</teleport>
</div>
</template>
<script>
import HelloWorld from './HelloWorld.vue'
export default {
components: {
HelloWorld
}
}
</script>
<style lang="scss" scoped>
</style>
HelloWorld.vue
<template>
<div>
hello world
</div>
</template>
<script>
export default {
}
</script>
<style lang="scss" scoped>
</style>

image.png
此文档主要内容来源于王红元老师的vue3+ts视频教程