Vue <Teleport> 元件
示例
使用內建的 <Teleport>
元件將 <div>
元素移動到 <body>
的根部
<Teleport to="body">
<div id="redDiv">Hello!</div>
</Teleport>
執行示例 »
更多示例請參見下方。
定義和用法
內建的 <Teleport>
元件與 to
prop 一起使用,可以將元素從當前 HTML 結構移出,並放入已掛載到 DOM 中的另一個元素。
要檢視元素是否真的透過 <Teleport>
元件移動到其他位置,您可能需要右鍵單擊並檢查頁面。
傳送的元素會出現在目標位置中已掛載的其他元素之後。因此,如果多個元素被傳送到同一個目標位置,則最後傳送的元素將出現在其他已傳送元素下方。
如果使用 <Teleport>
來移動元件,那麼與該元件的通訊(透過 provide/inject 或 prop/emit)仍然像以前一樣工作,就好像元件沒有被移動一樣。
此外,如果一些內容透過 <Teleport>
被移出元件,Vue 會確保元件在 <script>
和 <style>
標籤中的相關程式碼仍然對被移動的內容有效。請參見下面的示例。
Props
Prop | 描述 | |
---|---|---|
to | 必需。字串。指定目標的名稱 | 執行示例 » |
disabled | 可選。布林值。指定是否應停用 teleport 功能 | 執行示例 » |
更多示例
示例
即使 <div>
元素在編譯後不再位於元件內部,<style>
和 <script>
標籤中的相關程式碼仍然對傳送的 <div>
元素有效。
CompOne.vue
:
<template>
<div>
<h2>Component</h2>
<p>This is the inside of the component.</p>
<Teleport to="body">
<div
id="redDiv"
@click="toggleVal = !toggleVal"
:style="{ backgroundColor: bgColor }"
>
Hello!<br>
Click me!
</div>
</Teleport>
</div>
</template>
<script>
export default {
data() {
return {
toggleVal: true
}
},
computed: {
bgColor() {
if (this.toggleVal) {
return 'lightpink'
}
else {
return 'lightgreen'
}
}
}
}
</script>
<style scoped>
#redDiv {
margin: 10px;
padding: 10px;
display: inline-block;
}
#redDiv:hover {
cursor: pointer;
}
</style>
執行示例 »
示例
布林值 disabled
prop 透過一個按鈕切換,以便 <div>
元素可以被傳送或不被傳送。
CompOne.vue
:
<template>
<div>
<h2>Component</h2>
<p>This is the inside of the component.</p>
<button @click="teleportOn = !teleportOn">Teleport on/off</button>
<Teleport to="body" :disabled="teleportOn">
<div id="redDiv">Hello!</div>
</Teleport>
</div>
</template>
<script>
export default {
data() {
return {
teleportOn: true
}
}
}
</script>
<style scoped>
#redDiv {
background-color: lightcoral;
margin: 10px;
padding: 10px;
width: 100px;
}
</style>
執行示例 »
相關頁面
Vue 教程:Vue Teleport