天天看点

Vue3第九章(异步组件,Suspense代码分包)

创建一个组件,模拟异步获取数据

A/index.vue

<template>
  <div>
    <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 lang="scss" scoped></style>

           

server.ts

type NameList = {
    name: string
}

export const axios = (url:string):Promise<NameList[]> =>{
    return new Promise((resolve)=>{
        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)
    })
}
           

data.json

[
    {
        "name": "科技与狠活1"
    },
    {
        "name": "科技与狠活2"
    },
    {
        "name": "科技与狠活3"
    }
]
           

将组件A变为异步组件

通过import()方法导入的组件就变为了异步组件,并使用defineAsyncComponent

调用的时候使用Suspense,#fallback展示未请求到数据时展示的状态

<template>
  <div>
    <Suspense>
     <template #default>
      <A></A>
     </template>
     <template #fallback>
      <div>
        lodding
      </div>
     </template>
    </Suspense>  
  </div>
</template>

<script setup lang='ts'>
import {defineAsyncComponent} from 'vue'
const A = defineAsyncComponent(()=> import('../../components/A/index.vue'))
</script

           

继续阅读