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是使用其他方式实现这种方式的
原文章地址欢迎访问

相关推荐
apollo_qwe3 分钟前
前端缓存深度解析:从基础到进阶的实现方式与实践指南
前端
学习CS的小白11 分钟前
跨域问题详解
vue.js·后端
周星星日记12 分钟前
vue中hash模式和history模式的区别
前端·面试
Light6012 分钟前
Vue 高阶优化术:v-bind 与 v-on 的实战妙用与思维跃迁
前端·低代码·vue3·v-bind·组件封装·v-on·ai辅助开发
周星星日记12 分钟前
5.为什么vue中使用query可以保留参数
前端·vue.js
lebornjose12 分钟前
javascript - webgl中绑定(bind)缓冲区的逻辑是什么?
前端·webgl
+VX:Fegn089515 分钟前
计算机毕业设计|基于springboot + vue作业管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
Tzarevich16 分钟前
现代前端开发工程化:从 Vite 到 Vue 3 多页面应用实战
vue.js·vite
瘦的可以下饭了17 分钟前
Day05- CSS 标准流、浮动、Flex布局
前端
前端无涯19 分钟前
React中setState后获取更新后值的完整解决方案
前端·react.js