1. 程式人生 > 其它 >骨架屏元件.vue

骨架屏元件.vue

1)定義基礎骨架元件結構

components/Skeleton/index.vue

<template>
  <div
    class="xtx-skeleton shan"
    :style="{ width: '60px', height: '30px' }"
  >
    <!-- 1 盒子-->
    <div class="block" :style="{ backgroundColor: '#efefef'}"></div>
    <!-- 2 閃效果 xtx-skeleton 偽元素 --->
  </div>
</template>
<script>
export default {
  name: 'XtxSkeleton'
}
</script>
<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%;
  }
}
</style>

  

2)props設計

我們把骨架的寬度(width)、高度(height)、背景色(backgroundColor)定義為props,由使用者自定義傳入定製效果

<template>
  <div
    class="xtx-skeleton shan"
+    :style="{ width: width + 'px', height: height + 'px' }"
  >
    <!-- 1 盒子-->
+    <div class="block" :style="{ backgroundColor: bg }"></div>
    <!-- 2 閃效果 xtx-skeleton 偽元素 --->
  </div>
</template>
<script>
export default {
  name: 'XtxSkeleton',
  // 容許定製的引數包括: 背景/寬度/高度
+  props: {
+    bg: {
      type: String,
      default: '#efefef'
    },
+    width: {
      type: String,
      default: '100'
    },
+    height: {
      type: String,
      default: '100'
    }
+  }
}
</script>

  

3)測試元件props

playground/index.vue

<!-- 骨架元件測試 -->
<XtxSkeleton width="100" height="30" bg="blue"/>