同步组件引入方式
import List from './List.vue'
异步组件引入方式
import { onMounted, ref, defineAsyncComponent } from '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)
}, 4000)
})
},
loadingComponent: LoadingComponent,
delay: 200,
errorComponent: ErrorComponent,
timeout: 3000,
})
Inde.vue:
<script setup lang="ts">
import { onMounted, ref, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
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)
}, 4000)
})
},
loadingComponent: LoadingComponent,
delay: 200,
errorComponent: ErrorComponent,
timeout: 3000,
})
const router = useRouter()
const handleJump = (path: any) => {
router.push(path)
}
onMounted(() => {})
</script>
<template>
<div>
me
<button @click="() => handleJump('/home')">home</button>
<List></List>
</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>
ErrorComponent.vue:
<script setup lang="ts">
import { onMounted, ref } from 'vue'
onMounted(() => {})
</script>
<template>
<div>ErrorComponent</div>
</template>
官方教程
https://cn.vuejs.org/guide/components/async.html