1 app.vue
<template>
<div style="display:flex;">
<Suspense>
<!-- 默认插槽方式引用-->
<template #default>
<A></A>
</template>
<!-- fallback 组件没显示前先显示loading... -->
<template #fallback>
<div>
loading...
</div>
</template>
</Suspense>
</div>
</template>
//同步组件引用方式
//import A from './components/zj.vue'
//异步组件引用方式--需要配合Suspense使用
const A = defineAsyncComponent(()=>import('./components/zj.vue'))
2 组件zj.vue
<template>
<div>
<div :key="item" v-for="item in list">
{{ item.name }}
</div>
</div>
</template>
<script setup lang='ts'>
import{ref,reactive} from 'vue'
import {axios} from '../lib/server'
const list = await axios('/public/data.json')
setTimeout(() => {
console.log(list,'+++++++++++')
}, 2000);
</script>
3 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){
resolve(JSON.parse(xhr.responseText))
}
}
xhr.send(null);
})
}
4 data.json
[
{
"id":1, "name":"张三"
},
{
"id":2,"name":"李四"
},
{
"id":3,"name":"王五"
},
{
"id":4,"name":"赵柳"
}
]