随笔 - 12  文章 - 0  评论 - 0  阅读 - 6091

Vue3系列10--异步组件&代码分包&suspense

异步组件

在大型应用中,我们可能需要将应用分割成小一些的代码块 并且减少主包的体积,这时候就可以使用异步组件

顶层 await:在setup语法糖里面 使用方法,<script setup> 中可以使用顶层 await。结果代码会被编译成 async setup()

在项目进行打包后 会生成打包后的文件:

dist/index.html  程序入口 
dist/assets/index.e0b7c3a3.css 
dist/assets/index.c3955c07.js  主逻辑

在用户访问的时候,会加载index.html,html回去加载index.c3955c07.js ,如果这个文件太大,就会出现白屏。可以通过异步组件来优化。

(1)在public\data.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
    {
        "name":"模拟后端接口1"
    },
    {
        "name":"模拟后端接口2"
    },
    {
        "name":"模拟后端接口3"
    },
    {
        "name":"模拟后端接口4"
    }
]

(2)src\components\A\server.ts建立请求接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
type NameList = {
    name: string
}
 
export const axios = (url: string): Promise<NameList[]> => { //传入url,返回NameList数组
    return new Promise((resolve) => {
        let xhl: XMLHttpRequest = new XMLHttpRequest() // 去调用接口
        xhl.open('GET', url) // 获取数据
        xhl.onreadystatechange = () => { // 变化的时候就调用
            if (xhl.readyState === 4 && xhl.status) { // 调用完成,且接口正常
                setTimeout(() => {
                    resolve(JSON.parse(xhl.responseText)) // 返回的格式
                }, 2000);
            }
        }
        xhl.send(null) //发送数据
    })
}

(3)在src\components\A\index.vue文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
    <div>
        我是组件A
        <div :key="item.name" v-for="item in list">
            {{item.name}}
        </div>
    </div>
</template>
 
 
<script setup lang="ts">
import { axios } from './server';
const list = await axios('./data.json')
console.log(list)
 
</script>
 
 
<style scoped lang="less">
 
</style>

(4)在src\App.vue引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<template>
  <div>
    <Suspense>
      <template #default>
        <!-- 组件加载完成时候调用 -->
        <A></A>
      </template>
      <template #fallback>
        <!-- 组件加载的时候调用,加载完成后就会替换掉 -->
        <div>
          loading...
        </div>
      </template>
    </Suspense>
  </div>
</template>
 
<script setup lang="ts">
// import A from './components/A/index.vue'  // 改成异步组件,不能这么引入,数据显示不出来
import { ref, defineAsyncComponent } from 'vue'
const name = ref<string>('header')
 
const A = defineAsyncComponent(() => import('./components/A/index.vue'))  // 引入后,还需要配合suspense使用
// 只能通过import函数形式引入,单遇到awite的时候,把我们的逻辑拆分出去,打包的时候就多包
</script>
posted on   LotusFlower  阅读(426)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示