骨架屏
vue3的骨架屏使用开源包vue-content-loader
npm i vue-content-loader
npm地址:https://www.npmjs.com/package/vue-content-loader
骨架组件页面
<template>
<content-loader></content-loader>
</template>
<script>
import { ContentLoader } from 'vue-content-loader'
export default {
components: {
ContentLoader
}
}
</script>
<style>
</style>
内容页面
需要是一个异步组件 所以给setup添加async
<template>
<div>
<img :src="imgurl" alt="" class="ahufa">
</div>
</template>
<script>
import bg from '../../public/img1.jpg'
//使用Promise模拟一个异步请求 1.5秒以后把图片地址传给imgurl
const getBgc = () => {
return new Promise((resolve)=>{
setTimeout(()=>{
resolve(bg)
},1500)
})
}
export default {
在正常情况下是不能给setup()添加async的 但Suspense要求为一个异步组件
async setup(){
const imgurl = await getBgc()
return {imgurl}
}
}
</script>
<style>
.ahufa {
height: 600px;
}
</style>
App.vue
使用vue3新增的Suspense API
https://v3.cn.vuejs.org/guide/migration/suspense.html#%E4%BB%8B%E7%BB%8D
用法
<Suspense>
<<template #default>
<!-- 包含异步内容组件区域-->
</template>
<template #fallback>
<!-- 骨架屏占位区域 -->
</template>
</Suspense>
<template>
<div>
<Suspense>
<template #default>
<!--包含异步内容组件区域-->
<Asyncgay></Asyncgay>
</template>
<template #fallback>
<!-- 骨架屏占位区域 -->
<Loader></Loader>
</template>
</Suspense>
</div>
</template>
<script>
import Loader from './components/Loader.vue'
import Asyncgay from './components/Asyncgay.vue'
export default {
name: 'App',
components: {
Loader,Asyncgay
},
}
</script>