vue异步组件按需加载
一、注册组件时,使用()=>import(‘组件路径’)
<template>
<div class="home">
<button @click="change">加载Icon组件</button>
<icon v-if="(isShow)" />
</div>
</template>
<script>
// import Icon from ;
export default {
name: "home-index",
components: {
Icon:()=>import("./icon")
},
data(){
return {
isShow:false
}
},
methods: {
change(){
this.isShow = !this.isShow
}
},
};
</script>
效果:
点击“加载Icon组件”按钮前,页面并没有加载Icon组件的js:
点击“加载Icon组件”按钮后,页面加载了Icon组件的js:
二、使用异步组件工厂函数实现懒加载
<template>
<div class="home">
<button @click="change">加载Icon组件</button>
<async_icon v-if="isShow"/>
</div>
</template>
<script>
import loading from "./loading";
import page404 from "./page404";
const async_icon = ()=>({
// 要加载的组件
component:import("./icon"),
// 加载过程中展示的组件
loading:loading,
// 加载失败时展示的组件
error:page404,
// 延时加载时间
delay:500,
// 超时时间
timeout:2000,
})
export default {
name: "home-index",
components: {
async_icon
},
data(){
return {
isShow:false
}
},
methods: {
change(){
this.isShow = !this.isShow
}
},
};
</script>
效果:
在慢3G的情况下,点击“加载Icon组件”按钮后,页面加载优先加载loading组件:
再加载Icon组件: