【学习笔记】Vue3之Teleport

Vue3之Teleport

 

原文:https://vue3js.cn/docs/zh/guide/teleport.html#%E4%B8%8E-vue-components-%E4%B8%80%E8%B5%B7%E4%BD%BF%E7%94%A8

 

 

看一段代码:

复制代码
const app = Vue.createApp({})

app.component('modal-button', {
    template: `
        <button @click="modalOpen = true">
            Open full screen modal!(With teleport!)
        </button>

        <teleport to="body">
            <div v-if="modalOpen" class="modal">
                <div>
                    I'm a teleported modal!
                    (My parent is "body")
                    <button @click="modalOpen = false">关闭</button>
                </div>
            </div>
        </teleport>
    `,
    data() {
        return {
            modalOpen: false
        }
    }
})

app.mount('#app')
复制代码

 

与Vue components一起使用

如果<teleport>包含Vue组件,则它仍将是<teleport>父组件的逻辑子组件:

复制代码
const app = Vue.createApp({
    template: `
        <h1>Root instance</h1>
        <parent-component />
    `
})

app.component('parent-component', {
    template: `
        <h2>This is a parent component</h2>
        <teleport to="#endofbody">
            <child-component name="John" />
        </teleport>
    `
})

app.component('child-component', {
    props: ['name'],
    template: `
        <div>Hello, {{ name }}</div>
    `
})
复制代码

在这种情况下,即使在不同的地方渲染child-component,它仍将是parent-component的子级,并将从中接收name prop

这也意味着来自父组件的注入按预期工作,并且子组件将嵌套在Vue Devtools中的父组件之下,而不是放在实际内容移动到的位置。

 

在同一目标上使用多个teleport

一个常见的用例场景是一个可重用的<Modal>组件,它可能同时有多个实例处于活动状态。

复制代码
<teleport to="#modals">
    <div>A</div>
</teleport>
<teleport to="#modals">
    <div>B</div>
</teleport>

<!-- result -->
<div id="modals">
    <div>A</div>
    <div>B</div>
</div>
复制代码

 

teleport API

原文:https://vue3js.cn/docs/zh/api/built-in-components.html#teleport

【Props】

to - string,需要prop,必须是有效的查询选择器或HTMLElement(如果在浏览器环境中使用)。指定将在其中一栋<teleport>内容的目标元素

复制代码
  <!-- 正确 -->
  <teleport to="#some-id" />
  <teleport to=".some-class" />
  <teleport to="[data-teleport]" />

  <!-- 错误 -->
  <teleport to="h1" />
  <teleport to="some-string" />
复制代码

disabled - boolean. 此可选属性可用于禁用<teleport>的功能,这意味着其插槽内容将不会移动到任何位置,而是在您在周围父组件中指定了<teleport>的位置渲染。

<teleport to="#popup" :disabled="displayVideoInline">
    <video src="./my-movie.mp4">
</teleport>

请注意,这将移动实际的DOM节点,而不是被销毁和重新创建,并且它还将保持任何组件实例的活动状态。所有有状态的HTML元素(即播放的视频)都将保持其状态。

 

posted on   独自去流浪  阅读(1887)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示