Suspense组件
官网中有提到他是属于实验性功能:
<Suspense>
是一项实验性功能。它不一定会最终成为稳定功能,并且在稳定之前相关 API 也可能会发生变化。
<Suspense>
是一个内置组件,用来在组件树中协调对异步依赖的处理。它让我们可以在组件树上层等待下层的多个嵌套异步依赖项解析完成,并可以在等待时渲染一个加载状态。
意思就是此组件用来等待异步组件时渲染一些额外内容,让应用有更好的用户体验
要了解 <Suspense>
所解决的问题和它是如何与异步依赖进行交互的,我们需要想象这样一种组件层级结构:
<Suspense>
└─ <Dashboard>├─ <Profile>│ └─ <FriendStatus>(组件有异步的 setup())└─ <Content>├─ <ActivityFeed> (异步组件)└─ <Stats>(异步组件)
在这个组件树中有多个嵌套组件,要渲染出它们,首先得解析一些异步资源。如果没有 <Suspense>
,则它们每个都需要处理自己的加载、报错和完成状态。在最坏的情况下,我们可能会在页面上看到三个旋转的加载态,在不同的时间显示出内容。
有了 <Suspense>
组件后,我们就可以在等待整个多层级组件树中的各个异步依赖获取结果时,在顶层展示出加载中或加载失败的状态。
接下来看个简单的例子:
首先需要引入异步组件
import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
简洁一些就是用组件实现异步的加载的这么一个效果
Home父组件代码如下:
<template><div class="home"><h3>我是Home组件</h3><Suspense><template #default><Child /></template><template v-slot:fallback><h3>Loading...</h3></template></Suspense></div>
</template><script >
// import Child from './components/Child'//静态引入
import { defineAsyncComponent } from "vue";
const Child = defineAsyncComponent(() => import("../components/Child"));
export default {name: "",components: { Child },
};
</script><style>
.home {width: 300px;background-color: gray;padding: 10px;
}
</style>
自组件Child
<template><div class="child"><h3>我是Child组件</h3>name: {{user.name}}age: {{user.age}}</div>
</template><script>
import { ref } from "vue";
export default {name: "Child",async setup() {const NanUser = () => {return new Promise((resolve, reject) => {setTimeout(() => {resolve({name: "NanChen",age: 20,});},2000);});};const user = await NanUser();return {user,};},
};
</script><style>
.child {background-color: skyblue;padding: 10px;
}
</style>
根据插槽机制,来区分组件, #default 插槽里面的内容就是你需要渲染的异步组件; #fallback 就是你指定的加载中的静态组件。
效果如下: