vue中定义了加载组件的方式,异步调用组件可以减小父组件的体积,加载显示更快
可以通过dynamic import异步导入的方式进行懒加载子组件,设置webpackChunkName定义该异步的chunk的名字,不设置,则默认使用id命名该chunk 源码中定义了vue组件中component的组件的注册有两种类型,其中异步组件也是两种类型, 下图:
export type AsyncComponent<Data=DefaultData<never>, Methods=DefaultMethods<never>, Computed=DefaultComputed, Props=DefaultProps>
= AsyncComponentPromise<Data, Methods, Computed, Props>
| AsyncComponentFactory<Data, Methods, Computed, Props>
// promise异步组件, 函数返回promise
export type AsyncComponentPromise<Data=DefaultData<never>, Methods=DefaultMethods<never>, Computed=DefaultComputed, Props=DefaultProps> = (
resolve: (component: Component<Data, Methods, Computed, Props>) => void,
reject: (reason?: any) => void
) => Promise<Component | EsModuleComponent> | void;
// 工厂函数,返回一个对象
export type AsyncComponentFactory<Data=DefaultData<never>, Methods=DefaultMethods<never>, Computed=DefaultComputed, Props=DefaultProps> = () => {
component: AsyncComponentPromise<Data, Methods, Computed, Props>;
loading?: Component | EsModuleComponent;
error?: Component | EsModuleComponent;
delay?: number;
timeout?: number;
}
异步组件: AsyncComponent
一: AsyncComponentFactory 二: AsyncComponentPromise
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<!-- <todo-list /> -->
<AsyncComponent />
<FoodList />
</div>
</template>
<script>
// import TodoList from './TodoList.vue'
import LoaingComponent from './Loading.vue'
import ErrorComponent from './ErrorComponent.vue'
// 异步组件,工厂函数
const AsyncComponent = () => ({
component: import(/* webpackChunkName: "todo" */'./TodoList.vue'),
delay: 300,
timeout: 5000,
loading: LoaingComponent, //delay设置的时间内将调用该加载组件
error: ErrorComponent //加载组件超出timeout设置的时间,将显示error组件
})
// import FoodList from './FoodList'
export default {
components: {
AsyncComponent,
FoodList: ()=>import(/* WebpackChunName: "FoodList" */'./FoodList.vue') },//异步路由
name: 'HelloWorld',
props: {
msg: String
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
|