封装骨架屏组件

159 阅读1分钟

思路分析:

  1. 封装骨架屏单元格组件
  2. 配置Vue插件并且配置全局组件
  3. main.js中导入并配置UI组件库这个插件
  4. 分类列表中使用骨架屏组件进行占位

1.创建并封装骨架屏组件

<template>
 <!-- shan这个类是为了增加过渡动画 -->
  <div class="shop-skeleton" :style="{width,height}" :class="{shan:animated}">
    <!-- 1 盒子-->
    <div class="block" :style="{backgroundColor:bg}"></div>
    <!-- 2 闪效果 shop-skeleton 伪元素 --->
  </div>
</template>
<script>
export default {
  name: 'ShopSkeleton',
  // 使用的时候需要动态设置 高度,宽度,背景颜色,是否闪下
  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">
.shop-skeleton {
  display: inline-block;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  .block {
    width: 100%;
    height: 100%;
    border-radius: 2px;
  }
 animation: fade 1s linear infinite alternate;
}
@keyframes fade {
  from {
    opacity: 0.2;
  }
  to {
    opacity: 1;
  }
.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.新建index.js来导出骨架屏组件

import ShopSkeleton from './shop-skeleton.vue'
// 扩展vue原有的功能:全局组件,自定义指令,挂载原型方法,注意:没有全局过滤器。
// 这就是插件
// vue2.0插件写法要素:导出一个对象,有install函数,默认传入了Vue构造函数,Vue基础之上扩展
// vue3.0插件写法要素:导出一个对象,有install函数,默认传入了app应用实例,app基础之上扩展

export default {
  install (app) {
    // 在app上进行扩展,app提供 component directive 函数
    // 如果要挂载原型 app.config.globalProperties 方式
    app.component(ShopSkeleton.name, ShopSkeleton)
  }
}

3.在main.js中挂载注册

import ShopUI from './components/library'

// 插件的使用,在main.js使用app.use(插件)
createApp(App).use(store).use(router).use(ShopUI).mount('#app')

4.最后在通过v-if和v-else使用骨架屏组件进行占位