异步组件
- 在大型应用中,我们可能需要将应用分割成小一些的代码块 并且减少主包的体积
正常我们打包 npm run build
生成dist目录
代码被打包进js中,然而实际开发中项目文件很多,会造成打包体积过大
正常打包.vue文件,会被打包到一个index.js中,体积过大的话影响用户体验
- 模仿接口数据
// data.json
[
{
"name": "z0s"
},{
"name": "z1s"
},{
"name": "z2s"
},{
"name": "z3s"
},{
"name": "z4s"
}
]
// 模仿发送请求
type NameLists = {
name: string
}
export const axios = (url:string):Promise<NameLists[]> => {
return new Promise((resolve, reject) =>{
let xhr:XMLHttpRequest = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
// 模拟接口返回
setTimeout(() => {
resolve(JSON.parse(xhr.responseText));
}, 2000);
}
}
xhr.send(null);
})
}
-异步的方式引用组件,需要配合Suspense
使用
<template>
<div>
<!-- 异步组件配合Suspense使用 -->
<Suspense>
<template #default>
<A></A>
</template>
<!-- 数据加载回来之前 -->
<template #fallback>
<div>loading....</div>
</template>
</Suspense>
</div>
</template>
- 异步加载,减少内存占用,提高性能
<script setup lang="ts">
import { defineAsyncComponent } from 'vue';
// import A from '../../components/A/index.vue'
// 异步组件方式引入 打包的时候会拆分出去
const A = defineAsyncComponent(()=>import('../../components/A/index.vue'))
</script>
-此时我们打包,会发现多出个js文件