封装一个骨架屏组件

344 阅读1分钟

骨架屏就是在页面数据尚未加载前先给用户展示出页面的大致结构,直到请求数据返回后再渲染页面,补充进需要显示的数据内容。常用于文章列表、动态列表页等相对比较规则的列表页面。 很多项目中都有应用。

话不多说,上组件:

<!-- 骨架组件 -->
<script setup lang="ts">
//定义props接收
const { bg='skyblue', animated=false, fade=false } = defineProps<{
  width: number,
  height: number,
  bg: string,
  animated?: boolean,
  fade?: boolean
}>()
</script>
<template>
  <div
    class="skeleton"
    :style="{ width: width + 'px', height: height + 'px' }"
    :class="{ shan: animated, fade: fade }"
  >
    <!-- 1 盒子-->
    <div class="block" :style="{ backgroundColor: bg }">
    </div>
    <!-- 2 闪效果 skeleton 伪元素 --->
  </div>
</template>

<style scoped lang="less">
.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>

调用组件时需传入:

      width // 必传
      height  // 必传
      bg  // 背景色必传,默认色为'skyblue'
      animated  // 闪烁动画可不传
      fade  // 淡入淡出动画可不传