异步组件、suspense、Teleport、transition、transition-group
异步组件:通过延迟加载组件,只有在需要时才会加载它们。
异步组件在大型应用程序中非常有用,因为它们可以减少初始加载时间,并按需加载部分代码。
异步组件的常见使用场景
- 路由懒加载:在大型单页应用中,将路由对应的组件设置为异步组件,以减少初始加载时间。
- 按需加载:当页面中某些组件只有在用户触发特定操作时才需要加载时,可以使用异步组件。
<script setup lang="ts"> import { defineAsyncComponent } from 'vue'; // 定义异步组件,并配置加载、错误、延迟和超时 const AsyncComponent = defineAsyncComponent({ loader: () => import('./components/MyComponent.vue'), loadingComponent: () => import('./components/Loading.vue'), errorComponent: () => import('./components/Error.vue'), delay: 200, // 延迟200毫秒后显示加载组件 timeout: 3000, // 超时时间为3秒,超时后显示错误组件 retryWhenFail: true // 组件加载失败时,是否重新尝试加载 }); </script> <template> <div> <h1>Vue 3 异步组件示例</h1> <AsyncComponent /> </div> </template>
Suspense组件是一个非常有用的工具,专门用于处理异步组件的加载和状态管理。
Suspense会等待所有子组件(如 AsyncComponentA 和 AsyncComponentB)加载完成后才会渲染 #default 插槽的内容。
在此期间,#fallback 插槽的内容(例如加载动画)会显示。
<template>
<div>
<h1>等待多个异步组件</h1>
<Suspense>
<template #default>
<AsyncComponentA />
<AsyncComponentB />
</template>
<template #fallback>
<div>加载中...</div>
</template>
</Suspense>
</div>
</template>
<script setup lang="ts">
import { defineAsyncComponent } from 'vue';
// 定义多个异步组件
const AsyncComponentA = defineAsyncComponent(() => import('./components/ComponentA.vue'));
const AsyncComponentB = defineAsyncComponent(() => import('./components/ComponentB.vue'));
</script>
Teleport
它允许你将组件的模板内容渲染到 DOM 中的特定位置,而不是按照组件的正常层次结构渲染。
这对于处理模态框、通知、工具提示等需要在特定位置(如 body 根节点)渲染的元素特别有帮助。
ps:
1.可以自定义传送位置 支持 class id等 选择器
2.使用disabled 设置为 true则 to属性不生效 false 则生效
<template>
<div>
<h1>Vue 3 Teleport 示例</h1>
<button @click="showModal = true">打开模态框</button>
<!-- Teleport 将模态框内容移动到 body 元素 -->
<Teleport to="body">
xxxx
</Teleport>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const showModal = ref(false);
</script>
Teleport
1.v-enter-from:定义进入过渡的开始状态。在元素被插入之前生效,在元素被插入之后的下一帧移除。
2.v-enter-active:定义进入过渡生效时的状态。在整个进入过渡的阶段中应用,在元素被插入之前生效,在过渡/动画完成之后移除。这个类可以被用来定义进入过渡的过程时间,延迟和曲线函数。
3.v-enter-to:定义进入过渡的结束状态。在元素被插入之后下一帧生效 (与此同时 v-enter-from 被移除),在过渡/动画完成之后移除。
4.v-leave-from:定义离开过渡的开始状态。在离开过渡被触发时立刻生效,下一帧被移除。
5.v-leave-active:定义离开过渡生效时的状态。在整个离开过渡的阶段中应用,在离开过渡被触发时立刻生效,在过渡/动画完成之后移除。这个类可以被用来定义离开过渡的过程时间,延迟和曲线函数。
6.v-leave-to:离开过渡的结束状态。在离开过渡被触发之后下一帧生效 (与此同时 v-leave-from 被移除),在过渡/动画完成之后移除。
<button @click='flag = !flag'>切换</button>
<transition name='fade'>
<div v-if='flag' class="box"></div>
</transition>
//开始过度
.fade-enter-from{
background:red;
width:0px;
height:0px;
transform:rotate(360deg)
}
//开始过度了
.fade-enter-active{
transition: all 2.5s linear;
}
//过度完成
.fade-enter-to{
background:yellow;
width:200px;
height:200px;
}
//离开的过度
.fade-leave-from{
width:200px;
height:200px;
transform:rotate(360deg)
}
//离开中过度
.fade-leave-active{
transition: all 1s linear;
}
//离开完成
.fade-leave-to{
width:0px;
height:0px;
}
transition-group
用于对列表或一组元素应用过渡效果。
当你在列表中添加、删除或重新排序元素时,<transition-group> 可以为这些元素提供平滑的过渡动画。这在创建动态、交互丰富的用户界面时非常有用。
浙公网安备 33010602011771号