美文网首页
vue3 新特性:Fragment碎片化节点 和 telepor

vue3 新特性:Fragment碎片化节点 和 telepor

作者: 暴躁程序员 | 来源:发表于2023-04-13 18:57 被阅读0次

一、<Fragment> 碎片化节点

  1. 在 vue2 的组件中必须有且只有一个根元素标签,且此标签编译后真实存在 DOM 中,会增加代码体积

  2. 在 vue3 的组件中可以有多个根元素标签,构建时会生成<Fragment></Fragment>标签包裹这些根元素标签,Fragment 标签在编译后不会存在于 DOM 中,即:在 vue3 的组件中可以不用刻意定义根元素标签

<template>
  <h1>main</h1>
  <h1>content</h1>
</template>

二、<Teleport> 传送门

将其插槽内容渲染到 DOM 中的另一个位置。一般用于将组建挂载到 body 标签下

1. Teleport 的两个属性参数

  1. to 指定要挂在的位置,值为:css 选择器或 dom 元素
  2. disabled 是否禁用,值为:布尔值,默认为false不禁用

2. Teleport 的使用

  1. 将 HomeView 组件通过 Teleport 传送门挂在到 body 下
<template>
  <div>
    <h1>APP</h1>
    <Teleport to="body">
      <HomeView />
    </Teleport>
  </div>
</template>

<script setup>
import HomeView from "@/views/HomeView.vue";
</script>
  1. 定义 HomeView 组件
<template>
  <button @click="open = true">Open Modal</button>

  <div v-if="open" class="modal">
    <p>Hello from the modal!</p>
    <button @click="open = false">Close</button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      open: false,
    };
  },
};
</script>
<style scoped>
.modal {
  position: fixed;
  z-index: 999;
  top: 20%;
  left: 50%;
  width: 300px;
  margin-left: -150px;
}
</style>

相关文章

网友评论

      本文标题:vue3 新特性:Fragment碎片化节点 和 telepor

      本文链接:https://www.haomeiwen.com/subject/untzddtx.html