Vue3 异步组件实现骨架屏效果
具体代码实现
// axios.ts 文件 路径:src/server/axios.ts
export const axios ={
get<T>(url:string):Promise<T>{
return new Promise((resolve)=>{
const xhr = new XMLHttpRequest()
xhr.open('GET',url)
xhr.onreadystatechage = () =>{
if(xhr.readyState == 4 && xhr.status == 200){
setTimeout(()=>{
resolve(JSON.parse(xhr.responseText))
},2000)
}
}
})
}
}
其他.vue组件
// 在该组件内进行使用
import {axios} from '@server/axios.ts'
// 定义接收回来的数据的类型
interface Data{
data:{
name:string,
age:number,
url:string,
desc:string
}
}
// 使用封装好的axios 方法发送get请求拿到数据
// 顶层await 技术 异步组件
// 使用axios库中的get方法从本地路径'./data.json'处获取数据,然后将获取到的数据解构赋值给变量data。
const {data} = await axios.get<Data>('./data.json')
App.Vue文件
// 1.在该组件引入 异步组件.vue组件
// SyncVue 为 引入的组件
const SyncVue = defineAsyncComponent(()=> import('@/components/xxx.vue')
// <template> 里面
<template>
<Suspense>
// 我们要展示的组件 -- 异步组件 带有资源
<template #default>
<SyncVue></SyncVue>
</template>
// 加载的时候显示的组件 -- 骨架屏
<template #fallback>
<skeletonVue></skeletonVue>
</template>
</Suspense>
</template>