# 介绍
- 将大块代码分割为小块代码,然后异步加载代码块。
这样可以让首页部分代码优先加载,加快首页渲染速度, 其他代码块按需加载,加载过得代码块会被缓存起来,以避免重复渲染。
# 声明
1.通过Vue工厂函数
Vue.component('async-example', function(resolve, reject) {
resolve({
template: '<div>example</div>'
})
})
Vue.component('async-example', function(resolve, reject) {
require(['./async-component'], resolve)
})
工厂函数会收到一个resolve回调
通过工厂函数,返回一个promise对象
const asyncExample = () => Promise.resolve({
template: '<div>example</div>'
})
2.通过import()
Vue.component('async-example', () => import('./async-component'))
局部组件注册异步组件
new Vue({
components: {
asyncExample: () => import('./async-component')
}
})
# 高级异步组件
const asyncComponent = () => ({
component: './async-component',
delay: 200, // 延迟加载
error: errorComponent, // 加载失败显示组件
loading: loadingComponent, // 加载中显示组件
timeout: 2000 // 超时时间,默认Infinity
})
← v-show和v-if详解 路由懒加载 →