您好,欢迎访问一九零五行业门户网

Vue3异步组件Suspense如何使用

suspense组件官网中有提到他是属于实验性功能:
bb06e69d307cb52103d07d8f9dd385e5 是一项实验性功能。它不一定会最终成为稳定功能,并且在稳定之前相关 api 也可能会发生变化。
bb06e69d307cb52103d07d8f9dd385e5 是一个内置组件,用来在组件树中协调对异步依赖的处理。它让我们可以在组件树上层等待下层的多个嵌套异步依赖项解析完成,并可以在等待时渲染一个加载状态。
意思就是此组件用来等待异步组件时渲染一些额外内容,让应用有更好的用户体验
要了解 bb06e69d307cb52103d07d8f9dd385e5 所解决的问题和它是如何与异步依赖进行交互的,我们需要想象这样一种组件层级结构:
<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"> <h4>我是home组件</h4> <suspense> <template #default> <child /> </template> <template v-slot:fallback> <h4>loading...</h4> </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"> <h4>我是child组件</h4> 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 就是你指定的加载中的静态组件。
效果如下:
以上就是vue3异步组件suspense如何使用的详细内容。
其它类似信息

推荐信息