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

相关推荐
d***93518 小时前
springboot3.X 无法解析parameter参数问题
android·前端·后端
n***840719 小时前
十七:Spring Boot依赖 (2)-- spring-boot-starter-web 依赖详解
前端·spring boot·后端
likuolei1 天前
XSL-FO 软件
java·开发语言·前端·数据库
正一品程序员1 天前
vue项目引入GoogleMap API进行网格区域圈选
前端·javascript·vue.js
j***89461 天前
spring-boot-starter和spring-boot-starter-web的关联
前端
star_11121 天前
Jenkins+nginx部署前端vue项目
前端·vue.js·jenkins
im_AMBER1 天前
Canvas架构手记 05 鼠标事件监听 | 原生事件封装 | ctx 结构化对象
前端·笔记·学习·架构
JIngJaneIL1 天前
农产品电商|基于SprinBoot+vue的农产品电商系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设·农产品电商系统
Tongfront1 天前
前端通用submit方法
开发语言·前端·javascript·react
c***72741 天前
SpringBoot + vue 管理系统
vue.js·spring boot·后端