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

相关推荐
夏鹏今天学习了吗17 小时前
【性能优化】前端高性能优化策略
前端·性能优化
weixin_4277716120 小时前
css font-size 的妙用
前端·css
凤凰战士芭比Q21 小时前
web中间件——Nginx
前端·nginx·中间件
一 乐21 小时前
点餐|智能点餐系统|基于java+ Springboot的动端的点餐系统小程序(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·小程序·论文
视图猿人21 小时前
RxJS基本使用及在next.js中使用的例子
开发语言·javascript
bitbitDown1 天前
从零打造一个 Vite 脚手架工具:比你想象的简单多了
前端·javascript·面试
liangshanbo12151 天前
CSS 数学函数完全指南:从基础计算到高级动画
前端·css
码上成长1 天前
GraphQL:让前端自己决定要什么数据
前端·后端·graphql
冴羽1 天前
为什么在 JavaScript 中 NaN !== NaN?背后藏着 40 年的技术故事
前端·javascript·node.js
久爱@勿忘1 天前
vue下载项目内静态文件
前端·javascript·vue.js