异步组件
在大型应用中,我们可能需要将应用分割成小一些的代码块,并且只在需要的时候才从服务器加载一个模块。为了简化,Vue 允许你以一个工厂函数的方式定义你的组件,这个工厂函数会异步解析你的组件定义。Vue 只有在这个组件需要被渲染的时候才会触发该工厂函数,且会把结果缓存起来供未来重渲染。
# 全局异步组件,代码示例如下:
Vue.component("async-component",function(resolve, reject){
setTimeout(function () {
// 向 resolve回调传递组件定义
resolve({
template: '<div>我是异步组件</div>'
})
}, 1000)
});
new Vue({
el:"#app",
template:`
<div>
<async-component></async-component>
</div>
`
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 局部异步组件,代码示例如下:
new Vue({
el:"#app",
components:{
AsyncComponent:(resolve, reject)=>{
setTimeout(function () {
// 向 resolve回调传递组件定义
resolve({
template: '<div>我是异步组件</div>'
})
}, 1000)
}
},
template:`
<div>
<async-component></async-component>
</div>
`
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2022/05/30 12:17:36