当前位置:网站首页>suspense组件和异步组件

suspense组件和异步组件

2022-06-24 19:27:00 aliven1

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

  • 使用步骤:

    • 异步引入组件,使用defineAsyncComponent定义异步组件

      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>
      
      • 异步组件child中setup可以定义为异步函数,使用异步组件需要用Suspense包裹
<template>
	<div class="child">
		<h3>我是Child组件</h3>
		{
    {
    sum}}
	</div>
</template>

<script>
	import {
    ref} from 'vue'
	export default {
    
		name:'Child',
		async setup(){
    
			let sum = ref(0)
			let p = new Promise((resolve,reject)=>{
    
				setTimeout(()=>{
    
					resolve({
    sum})
				},1000)
			})
			return await p
		}
	}
</script>
原网站

版权声明
本文为[aliven1]所创,转载请带上原文链接,感谢
https://gudujian.blog.csdn.net/article/details/125414945