给多个异步组件提供一个统一的状态管理
使用前,有两个loading...
使用后, 只有一个loading...
Index.vue:
<script setup lang="ts">
import { onMounted, ref, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import Header from './Header.vue'
import LoadingComponent from './LoadingComponent.vue'
import ErrorComponent from './ErrorComponent.vue'
// import List from './List.vue'
// const List = defineAsyncComponent(() => import('./List.vue'))
// const List = defineAsyncComponent(() => {
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// let temp = import('./List.vue')
// resolve(temp as never)
// }, 2000)
// })
// })
const List = defineAsyncComponent({
loader: () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
let temp = import('./List.vue')
resolve(temp as never)
}, 1000)
})
},
loadingComponent: LoadingComponent,
delay: 200,
errorComponent: ErrorComponent,
timeout: 3000,
})
const router = useRouter()
const handleJump = (path: any) => {
router.push(path)
}
onMounted(() => {})
</script>
<template>
<div>
<Suspense>
<div>
me
<button @click="() => handleJump('/home')">home</button>
<Header></Header>
</div>
<template #fallback>
<div>loading...</div>
</template>
</Suspense>
<List></List>
</div>
</template>
Header.vue:
<script setup lang="ts">
let res: any = { count: 0 }
res = await new Promise((resolve) => {
setTimeout(() => {
resolve({ count: 1 })
}, 2000)
})
console.log('res', res)
import { onMounted, ref } from 'vue'
onMounted(() => {})
</script>
<template>
<div>header {{ res.count }}</div>
</template>
List.vue:
<script setup lang="ts">
import { onMounted, ref } from 'vue'
onMounted(() => {})
</script>
<template>
<div>
list
</div>
</template>
LoadingComponent.vue:
<script setup lang="ts">
import { onMounted, ref } from 'vue'
onMounted(() => {})
</script>
<template>
<div>loading...</div>
</template>
官方文档
https://cn.vuejs.org/guide/built-ins/suspense.html
人工智能学习网站
https://chat.xutongbao.top