一、src/components下新建目录 skeleton/index.vue
骨架屏本质上就是一个div元素,给它设置宽高背景色 动画等.. 就能得到不一样的骨架屏样式
<script setup lang="ts" name="XtxSkeleton">
defineProps({
bg: {
type: String,
default: "#efefef",
},
width: {
type: Number,
required: true,
},
height: {
type: Number,
required: true,
},
animated: {
type: Boolean,
default: false,
},
fade: {
type: Boolean,
default: false,
},
});
</script>
<template>
<div
class="xtx-skeleton"
:style="{
width: width + 'px',
height: height + 'px',
}"
:class="{
shan: animated,
fade,
}"
>
<!-- 盒子-->
<div
class="block"
:style="{
backgroundColor: bg,
}"
></div>
</div>
</template>
<style scoped lang="less">
.xtx-skeleton {
display: inline-block;
position: relative;
overflow: hidden;
vertical-align: middle;
.block {
width: 100%;
height: 100%;
border-radius: 2px;
}
}
.shan {
&::after {
content: "";
position: absolute;
animation: shan 1.5s ease 0s infinite;
top: 0;
width: 50%;
height: 100%;
background: linear-gradient(
to left,
rgba(255, 255, 255, 0) 0,
rgba(255, 255, 255, 0.3) 50%,
rgba(255, 255, 255, 0) 100%
);
transform: skewX(-45deg);
}
}
@keyframes shan {
0% {
left: -100%;
}
100% {
left: 120%;
}
}
.fade {
animation: fade 1s linear infinite alternate;
}
@keyframes fade {
from {
opacity: 0.2;
}
to {
opacity: 1;
}
}
</style>
二、骨架屏注册成全局组件
// 统一的注册所有的全局组件
// 骨架屏组件
import XtxSkeleton from '@/components/skeleton/index.vue'
import { App } from 'vue'
export default {
install(app: App) {
app.component(XtxSkeleton.name, XtxSkeleton)
},
}
三、main.ts注册成全局插件
// 导入全局组件 ,挂载到App上
import XtxUI from './components'
createApp(App).use(XtxUI).use(router).use(createPinia()).mount('#app')
四、页面中使用
<script setup lang="ts">
import { ref } from "vue";
const list = ref([]);
</script>
<template>
<div>
<!-- 如果list数据存在,渲染数据 -->
<template v-if="list">
<!-- 数据渲染 -->
</template>
<!-- 否则渲染骨架屏 -->
<template v-else>
<XtxSkeleton
:width="60"
:height="18"
style="margin-right: 5px"
bg="rgba(255,255,255,0.2)"
animated
/>
<XtxSkeleton
:width="50"
:height="18"
bg="rgba(255,255,255,0.2)"
animated
/>
</template>
</div>
</template>