Vue3中的那些新增的内置组件

1.Fragment(相当于Vue2中的根标签)

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

2.Teleport(传送组件)

  • 什么是Teleport(远程传送的意思)?—— Teleport 是Vue3中的一个内置组件,是一种能够将我们的组件html结构移动到指定位置(DOM节点)的技术。
  • 使用方法: 使用Teleport标签包裹住想要传送的html标签元素,随后再在Teleport标签中的to属性当中指向传送位置即可,这里的传送位置可以是css选择器,可以是标签元素,不过Vue团队建议我们把to指向body标签。
  • 好处:我们在实际开发当中可能会遇到弹窗提示,但是项目的html层级是一环扣一环的,你想要给里面的层级设定弹窗居中,那么以后你往上的任一层级发生改变都会对你的居中有影响,但是使用teleport组件,可以将弹窗结构传送到body标签当中,这样你就只有一个父元素,这时做居中就显得更加的加单方便,也不用担心层级的问题了!

代码展示:

  • Dialog组件当中(省略css部分)
    <template>
    <div>
    <button @click="isShow = true">点我弹个窗</button>
    <!-- 在body标签当中添加这个组件,即body标签成为这个html结构的父元素 -->
    <teleport to="body">
    <div v-if="isShow" class="mask">
    <div class="dialog">
    <h3>我是一个弹窗</h3>
    <h1>内容</h1>
    <button @click="isShow = false">关闭弹窗</button>
    </div>
    </div>
    </teleport>
    </div>
    </template>

    <script>
    import {ref} from 'vue'
    export default {
    name:'Dialog',
    setup(){
    let isShow = ref(false)
    return {isShow}
    }
    }
    </script>
  • Son组件当中调用
    <template>
    <div class="son">
    <h3>我是Son组件</h3>
    <Dialog/>
    </div>
    </template>

    <script>
    import Dialog from './Dialog.vue'
    export default {
    name:'Son',
    components:{Dialog}
    }
    </script>

结果展示:

image

3.Suspense(异步组件)

  • 等待异步组件时渲染一些额外内容,让应用有更好的用户体验

  • 使用场景:

    • 在页面加载之前显示加载动画(后台获取数据过慢导致数据显示到页面时间过长)

    • 显示占位符内容

    • 处理延迟加载的图像

  • 使用步骤:

    • 异步引入组件
import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
  • 使用Suspense包裹组件,并配置好defaultfallback
<template>
<div class="app">
<h3>我是App组件</h3>
<Suspense>
<template v-slot:default>
<Child/>
</template>
<template v-slot:fallback>
<h3>加载中.....</h3>
</template>
</Suspense>
</div>
</template>