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

[
    {
        "name":"模拟后端接口1"
    },
    {
        "name":"模拟后端接口2"
    },
    {
        "name":"模拟后端接口3"
    },
    {
        "name":"模拟后端接口4"
    }
]

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

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文件

<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引用

<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>

标签: Javascript

添加新评论