vue3 Suspense

vue3新增了异步组件,和一堆api。。文档

最近使用vue3开发中,需要在setup中使用async获取接口数据

// ...
async setup () {
	await $http.getUserInfo().then((res: any) => {
		//... 处理数据
	})
	await $http.getApplicationInfo().then((res: any) => {// ...})
	return {
		//....
	}
}

运行项目!!。然后发现页面一片空白。找了半天没发现问题所在,然后只能百度。发现需要在父节点中加上 Suspense组件。。
…这玩意极端点可以加载跟节点上

<Suspense>
	<!-- 子节点。。。 -->
	<Children></Children>
</Suspense>

!!然后发现页面可以访问了。

但是!!这个时候我想要在页面加载完成功之后处理一些内容

// ...
async setup () {
	await $http.getUserInfo().then((res: any) => {
		//... 处理数据
	})
	await $http.getApplicationInfo().then((res: any) => {// ...})
	onMounted(() => {
		//...页面加载完成之后需要做其他操作
		debugger
	})
	return {
		//....
	}
}

。。然后发现这个 debugger 一直进不去。
这个时候发现控制台有个警告:onMounted is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

。也就是说 如果你使用了 async setup(),那么在如果想要使用 onMounted 生命周期的话,需要确保在第一个 await 语句之前注册 生命周期钩子

修改代码:

// ...
async setup () {
	onMounted(() => {
		//...页面加载完成之后需要做其他操作
		debugger
	})
	await $http.getUserInfo().then((res: any) => {
		//... 处理数据
	})
	await $http.getApplicationInfo().then((res: any) => {// ...})
	return {
		//....
	}
}

这个时候发现页面加载完成之后 debugger 进来了。。

Suspense组件

Suspense组件是有两个插槽的。默认的 default 是在异步组件加载完成之后显示,还有个插槽 fallback 代表异步组件加载中显示

<template>
	<Suspense>
		<template #default>
			<!-- 异步组件加载完成之后展示的控件 -->
		</template>
		<template #fallback>
			<!-- 异步组件加载中展示的控件 -->
		</template>
	</Suspense>
</template>
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐