Vue异步组件以及配合suspense使用

Vue异步组件以及配合suspense使用

异步组件的使用场景是,当一个项目被分成很多歌组件的时候,当在一个组件中需要到另一个组件的时候,可以使用异步组件的方式异步请求一个服务器上的组件。

异步组件的核心是使用 Vue.defineAsyncComponent 方法,参数是一个Promise工厂函数。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 引入Vue.defineAsyncComponent方法
const {
createApp,
defineAsyncComponent
} = Vue

const app = createApp({})

app.component('async-example', defineAsyncComponent(
() =>
new Promise((resolve, reject) => {
resolve({
template: '<div>I am async!</div>'
})
})
))

或者如果使用webpack的话可以这样动态导入组件:

1
2
3
4
5
6
7
import {
defineAsyncComponent
} from 'vue'

app.component('async-component', defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
))

在局部注册的组件中使用动态组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
import {
createApp,
defineAsyncComponent
} from 'vue'

createApp({
// ...
components: {
AsyncComponent: defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
)
}
})

suspense的作用:在异步组件渲染完毕之前展示一些内容用于提升用户体验。

示例:

1
2
3
4
5
6
7
8
9
10
11
<!-- 这里async-component是一个已经定义好的异步组件,代码省略 -->
<suspense>
<!-- 异步组件加载成功时展示 -->
<template #default>
<async-component></async-component>>
</template>
<!-- 异步组件加载失败时展示 -->
<template #fallback>
<p>异步组件加载失败!</p>
</template>
</suspense>

评论