学习Vue3值得注意的新特性系列之(二)

学习Vue3值得注意的新特性系列之(二)

值得注意的新特性

Vue 3 中需要关注的一些新功能包括:

  1. 组合式 API

  2. Teleport

  3. 片段

  4. 触发组件选项

  5. [createRenderer API 来自 @vue/runtime-core

    ](github.com/vuejs/vue-n…

  6. [单文件组件组合式 API 语法糖 (<script setup>)

    ](github.com/vuejs/rfcs/…

  7. [单文件组件状态驱动的 CSS 变量 (<style vars>)

    ](github.com/vuejs/rfcs/…

  8. 单文件组件 <style scoped> 现在可以包含全局规则或只针对插槽内容的规则

Teleport

  • Teleport 是什么?它解决的是什么问题?

Teleport 中文译为:

  • v. 心灵运输(物体、人);远距离传送
  • n. 通信卫星;心灵传输

有许多小伙伴/大佬 也称为任意门,瞬间移动组件,小伙伴们可以根据自己的理解,樱小桃(我)统一以英文 Teleport 来讲。

Teleport 是一种能够将我们的模板渲染至指定DOM节点,不受父级stylev-show等属性影响,但dataprop数据依旧能够共用的技术;类似于 ReactPortal

teleport标签包含to属性用于指定挂载的目标DOM节点

  <template>
    <div class="hello">
      <span>Hello World</span>

      <teleport to="#teleport-target">
        <span>Hello Teleport</span>
      </teleport>
    </div>
  </template>



<script>
  export default {
    beforeCreate() {
      const node = document.createElement("div");
      node.id = "teleport-target";
      document.body.appendChild(node);
    },
  };
  </script>
 

如图:

学习Vue3值得注意的新特性系列之(二)

**那它解决的是什么问题?**Teleport多应用于逻辑属于该组件,而从技术角度讲,却要把它移动到其他节点(body或者指定ID的元素) 里。最常见的场景就是创建一个包含全屏模式的组件,逻辑存在于组件内,但是基于css样式,却要把他移动到 body 元素上。vue3官方文档:Teleport 提供了一种干净的方法,允许我们控制在 DOM 中哪个父节点下呈现 HTML,而不必求助于全局状态或将其拆分为两个组件。

使用场景

与 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> 组件可以将其内容挂载到同一个目标元素。顺序将是一个简单的追加——稍后挂载将位于目标元素中较早的挂载之后。

<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>
 

未完待续。。。。。

下一节:在 Vue 3 中,组件现在正式支持多根节点组件,即片段!

往期文章回顾

学习Vue3值得注意的新特性系列之(一)

(0)
上一篇 2021年5月27日 上午2:07
下一篇 2021年5月27日 上午2:28

相关推荐

发表评论

登录后才能评论