×

Vue3开发特性:Teleport

作者:ceshi2021.05.28来源:Web前端之家浏览:3398评论:0
关键词:vue

Vue3开发特性:Teleport。

在本文中,我们将介绍:

  • Teleport 的目的

  • Teleport 的例子

  • 一些很有意思的代码交互

Teleport 的目的

首先是什么时候以及使用这个 Teleport 功能。

在开发较大的 Vue 项目时应该以可重用的逻辑去组织代码。但是当处理某些类型的组件(如模式、通知或工具提示)时,模板 HTML 的逻辑可能不会和我们希望渲染元素处于相同的文件中。

实际上在大多数情况下,与 Vue 的 DOM 完全分开处理相比,处理这些元素要容易得多。因为嵌套组件的位置、z-index 和样式等这些东西,可能由于需要处理其所有父对象的作用域而变得棘手。

而这些正是 Teleport 的用武之地。我们可以在逻辑所在的组件中编写模板代码,因为这样我们可以使用组件的数据或 props。

如果不用 Teleport,我们还必须担心事件传播会把逻辑从子组件传递给 DOM 树。

Teleport 是怎样工作的

假设有一些子组件,我们想在其中触发弹出的通知。正如刚刚讨论的那样,如果将通知以完全独立的 DOM 树渲染,而不是 Vue 的根 #app 元素,会更加简单。

首先编辑 index.html 并在 </body> 之前添加一个 <div>。

//index.html
<body>
   <div id="app"></div>
   <div id='portal-target'></div>
</body>

接下来创建触发渲染通知的组件。

//VuePortals.vue
<template>
  <div class='portals'>
    <button @click='showNotification'> Trigger Notification! </button>
    <teleport to='#portal-target'>
      <div class='notification'>
        This is rendering outside of this child component!
      </div>
    </teleport>
  </div>
</template>

<script>
import { ref } from 'vue'
export default {
  setup () {
    const isOpen = ref(false)

    var closePopup

    const showNotification = () => {
      isOpen.value = true

      clearTimeout(closePopup)

      closePopup = setTimeout(() => {
        isOpen.value = false
      }, 2000)
    }

    return {
      isOpen,
      showNotification
    }
  }
}
</script>

<style scoped>
  .notification {
    font-family: myriad-pro, sans-serif;
    position: fixed;
    bottom: 20px;
    left: 20px;
    width: 300px;
    padding: 30px;
    background-color: #fff;
  }
</style>

在这代码段中,按下按钮时,将渲染通知 2 秒钟。但是我们的主要目标是用 Teleport 获取通知并在 VUE 程序外部渲染。

如你所见,Teleport 有一个必填属性:to

to 属性使用有效的 DOM 查询字符串,它可以是:

  • 元素的 ID

  • 元素的类

  • 数据选择器

  • 响应查询字符串

由于我们在 #portal-target 中传递了代码,所以 Vue 程序将找到我们包含在 index.html 中的 #portal-target div,它会传送门户中的所有代码并将其渲染在该 div 中。

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/vue20210528a334.html

网友评论文明上网理性发言 已有0人参与

发表评论: