Vue Teleport
Vue 的 <Teleport>
標籤用於將內容移動到 DOM 結構中的不同位置。
<Teleport> 和 'to' 屬性
要將某些內容移動到 DOM 結構中的其他位置,我們使用 Vue 的 <Teleport>
標籤包裹內容,並使用 'to' 屬性來定義移動到的位置。
<Teleport to="body">
<p>Hello!</p>
</Teleport>
'to' 屬性的值以 CSS 符號表示法給出,因此,如果我們想將一些內容傳送到 body 標籤(如上面的程式碼所示),我們只需編寫 <Teleport to="body">
。
載入頁面後,我們可以透過檢查頁面來看到內容已被移至 body 標籤。
示例
CompOne.vue
:
<template>
<div>
<h2>Component</h2>
<p>This is the inside of the component.</p>
<Teleport to="body">
<div id="redDiv">Hello!</div>
</Teleport>
</div>
</template>
執行示例 »
如果我們右鍵單擊頁面並選擇“檢查”,我們可以看到紅色的 <div>
元素已被移出元件,並移到了 <body>
標籤的末尾。

我們也可以例如有一個帶有 id <div id="receivingDiv">
的標籤,然後透過使用 <Teleport to="#receivingDiv">
包裹我們想要傳送/移動的內容,將一些內容傳送/移動到該 <div>
中。
被傳送元素的指令碼和樣式
即使某些內容被 <Teleport>
標籤移出了元件,<script>
和 <style>
標籤中與被移動內容相關的程式碼仍然可以正常工作。
示例
儘管被傳送的 <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>
執行示例 »