Vue中封装一个骨架屏组件

骨架屏组件的目的:为了在加载过程中等待效果更好,封装一个骨架屏组件

封装一个组件,做占位使用,这个占位组件有个专业术语:骨架屏组件,暴露一些属性:高、宽、背景、是否有闪动画

skeleton.vue

<template>
  <div class="skeleton" :style="{width,height}" :class="{shan:animated}">
    <!-- 1 盒子-->
    <div class="block" :style="{backgroundColor:bg}"></div>
    <!-- 2 闪效果 skeleton 伪元素 --->
  </div>
</template>
<script>
export default {
  name: 'Skeleton',
  // 使用的时候需要动态设置 高度,宽度,背景颜色,是否闪下
  props: {
    bg: {
      type: String,
      default: '#efefef'
    },
    width: {
      type: String,
      default: '100px'
    },
    height: {
      type: String,
      default: '100px'
    },
    animated: {
      type: Boolean,
      default: false
    }
  }
}
</script>
<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%;
  }
}
</style>

可以将股价骨架屏组件注册成全局插件,这样就可以全局一起使用了

import Skeleton from './skeleton.vue'

export default {
  install (app) {
   
    app.component(Skeleton.name, XtxSkeleton)
  }
}

在main.js注册插件

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './mock'
+import XXXUI from './components/library'

import 'normalize.css'
import '@/assets/styles/common.less'
+// 插件的使用,在main.js使用app.use(插件)
+createApp(App).use(store).use(router).use(XxxUI).mount('#app')

使用注册的骨架屏组件

<template>
  <ul class="menu">
      <li :class="{active:categoryId===item.id}" v-for="item in list" :key="item.id" @mouseenter="categoryId=item.id">
        <RouterLink to="/">{{item.name}}</RouterLink>
// 有数据时显示数据
        <template v-if="item.children">
          <RouterLink to="/" v-for="sub in item.children" :key="sub.id">{{sub.name}}</RouterLink>
// 没有数据时显示骨架屏
        </template>
+        <span v-else>
+          <XtxSkeleton width="60px" height="18px" style="margin-right:5px" bg="rgba(255,255,255,0.2)" />
+          <XtxSkeleton width="50px" height="18px" bg="rgba(255,255,255,0.2)" />
+        </span>
      </li>
    </ul>

</template>

使用骨架屏后的效果:

没有数据的时候显示骨架屏

有数据时显示数据

 

 


版权声明:本文为weixin_55690518原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。