fragment

fragment

  • 在vue2中,组件必须有一个跟标签
  • 在vue3中,组件可以没有跟标签,内部会将多个标签包含在一个fragment虚拟元素中
  • 好处:减少标签层级,减小内存占用

teltport

  • 什么是teltport

teleport是一种能够将我们组件html结构移动到指定位置的技术

像是下面的代码不适用teleport:

teleport1:

vue 复制代码
<template>
  <div class="lim">
    teleport
    <teleport2>
    </teleport2>
  </div>
</template>

<script>
import Teleport2 from './teleport2.vue'

export default {
  name: "teleport1",
  components: { Teleport2 }
}
</script>

<style scoped lang="less">
.lim{
  padding: 20px;
  background-color: gray;
}
</style>

teleport2:

vue 复制代码
<template>
  <div class="lim2">
    teleport2
    <teleport3></teleport3>
  </div>
</template>

<script>
import Teleport3 from './teleport3.vue'

export default {
  name: "teleport2",
  components: { Teleport3 }
}
</script>

<style scoped lang="less">
.lim2{
  padding: 20px;
  background-color: rgba(128, 0, 128, 0.2);
}
</style>

teleport3:

vue 复制代码
<template>
  <div class="lim">
    teleport3
  </div>
  <test-dialog></test-dialog>
</template>

<script setup>

import TestDialog from './testDialog.vue'
</script>

<style scoped lang="less">
.lim {
  padding: 20px;
  background: #2c3e50;
  color: white;
}
</style>

testDialog:

vue 复制代码
<template>
  <div class="dialog">
    <el-button @click="show=true">弹窗</el-button>
    <div class="alertContent" v-if="show">
      <el-button @click="show=false">关闭</el-button>
      这是一个弹窗
    </div>
  </div>
</template>

<script setup>
import {  ref } from 'vue'
const show = ref(false)
</script>

<style scoped lang="less">
.alertContent {
  padding: 20px;
  background: #0d91fe;
}
</style>

run:

可以发现他的份层级是在teleport3的层级中的

但由于它是个弹窗,这样使用是很怪的,所以需要使用到teleport:

这里只有testDialog用teleport:

vue 复制代码
<template>
  <div class="dialog">
    <el-button @click="show=true">弹窗</el-button>
    <teleport to="html">
      <div class="alertContent" v-if="show">
        <el-button @click="show=false">关闭</el-button>
        这是一个弹窗
      </div>
    </teleport>
  </div>
</template>

<script setup>
import {  ref } from 'vue'

const show = ref(false)

</script>

<style scoped lang="less">
.alertContent {
  padding: 20px;
  background: #0d91fe;
}
</style>

run:

注意这里的<teleport to="html">它是关键

关于这个东西,在使用elementui plus中的图片预览组件就有用到,真的好用,而elementui是使用其他方式实现这种方式的
原文章地址欢迎访问

相关推荐
顾青14 分钟前
微信小程序 VisionKit 实战(二):静态图片人脸检测与人像区域提取
前端·微信小程序
hmfy14 分钟前
那些前端老鸟才知道的秘密
前端
野葳蕤15 分钟前
react总览
前端
不一样的少年_18 分钟前
她说想要浪漫,我把浏览器鼠标换成了柴犬,点一下就有烟花(附源码)
前端·javascript·浏览器
顾青18 分钟前
微信小程序实现身份证识别与裁剪(基于 VisionKit)
前端·微信小程序
星链引擎18 分钟前
技术深度聚焦版(侧重技术原理与代码细节)
前端
呵阿咯咯19 分钟前
ueditor富文本编辑器相关问题
前端
月弦笙音19 分钟前
【Vue3】Keep-Alive 深度解析
前端·vue.js·源码阅读
地方地方19 分钟前
手写 AJAX 与封装 MyAxios:深入理解前端网络请求
前端·javascript·面试
该用户已不存在25 分钟前
7个没听过但绝对好用的工具
前端·后端