認(rèn)識(shí)teleport內(nèi)置組件
在組件化開(kāi)發(fā)中,我們封裝一個(gè)組件A,在另外一個(gè)組件B中使用:
- 那么組件A中template的元素,會(huì)被掛載到組件B中template的某個(gè)位置;
- 最終我們的應(yīng)用程序會(huì)形成一顆DOM樹(shù)結(jié)構(gòu);
但是某些情況下,我們希望組件不是掛載在這個(gè)組件樹(shù)上的,可能是移動(dòng)到Vue app之外的其他位置: + 比如移動(dòng)到body元素上,或者我們有其他的div#app之外的元素上;
- 這個(gè)時(shí)候我們就可以通過(guò)teleport來(lái)完成;
Teleport是什么呢?
- 它是一個(gè)Vue提供的內(nèi)置組件,類(lèi)似于react的Portals;
- teleport翻譯過(guò)來(lái)是心靈傳輸、遠(yuǎn)距離運(yùn)輸?shù)囊馑迹?
它有兩個(gè)屬性:
-
to:指定將其中的內(nèi)容移動(dòng)到的目標(biāo)元素,可以使用選擇器; -
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目標(biāo)位置 -->
<div id="why"></div>
<!-- built files will be auto injected -->
</body>
</html>
App.vue
<template>
<div>
<teleport to="#why">
<h1>今天天氣不錯(cuò)</h1>
<!--如果teleport內(nèi)部有組件,組件的內(nèi)容也會(huì)一同掛載到目標(biāo)DOM內(nèi)部-->
<hello-world />
</teleport>
<!--如果使用過(guò)個(gè)teleport掛載到同一目標(biāo)Dom內(nèi),會(huì)一次按照屬性進(jìn)行掛載-->
<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
此文檔主要內(nèi)容來(lái)源于王紅元老師的vue3+ts視頻教程