• 【学习笔记】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元素(即播放的视频)都将保持其状态。

  • 相关阅读:
    内存分配问题
    C++ assert 的一点说明
    强大的stringstream
    C++中随机数
    C++ 中new
    C++ 中string 详解 转载自 博客园
    未命名名字空间
    使用ifstream和getline读取文件内容[c++]
    6.bootstrap练习笔记-缩略图和list-group
    3.bootstrap练习笔记-媒体内容
  • 原文地址:https://www.cnblogs.com/cathy1024/p/14026107.html
Copyright © 2020-2023  润新知