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

相关推荐
棉花糖超人4 分钟前
【从0-1的CSS】第3篇:盒子模型与弹性布局
前端·css·html
daols887 小时前
vue vxe-table 自适应列宽,根据内容自适应宽度的2种使用方式
vue.js·vxe-table
小小小小宇7 小时前
虚拟列表兼容老DOM操作
前端
悦悦子a啊7 小时前
Python之--基本知识
开发语言·前端·python
安全系统学习8 小时前
系统安全之大模型案例分析
前端·安全·web安全·网络安全·xss
涛哥码咖8 小时前
chrome安装AXURE插件后无效
前端·chrome·axure
OEC小胖胖9 小时前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
行云&流水9 小时前
Vue3 Lifecycle Hooks
前端·javascript·vue.js
Sally璐璐9 小时前
零基础学HTML和CSS:网页设计入门
前端·css
老虎06279 小时前
JavaWeb(苍穹外卖)--学习笔记04(前端:HTML,CSS,JavaScript)
前端·javascript·css·笔记·学习·html