在Vue3项目中封装一个Skeleton骨架效果组件

248 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第15天,点击查看活动详情

目的

为了在加载的过程中提高用户的等待体验,封装一个Skeleton骨架组件。

思路

  • 封装一个组件,用来在页面上数据没有加载出来之前,先占位。
  • 暴露组件的一些属性:weight,height,backgroundColor,animation。提高组件的可扩展性。
  • 公用组件,在全局注册。

封装代码

在src/components/library下新建Skeleton.vue

image.png

<template>
  <div class="skeleton" :style="{width,height}" :class="{shan:animated}">
    <!-- 1 盒子-->
    <div class="block" :style="{backgroundColor:bg}"></div>
    <!-- 2 动画 伪元素 --->
  </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>

全局注册

  1. 在src/components/library下新建index.js,专门用于扩展vue原有功能 image.png
// 扩展vue原有功能:全局组件,自定义指令等。注意v3里面没有过滤器
import Skeleton from './Skeleton.vue'

export default {
  install (app) {
    app.component(Skeleton.name, Skeleton)
  }
}
  1. 挂载到App上。在main.js中:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// 都是和重置样式相关的代码
import 'normalize.css'
import '@/assets/styles/common.less'

// 导入自己的UI库
import UI from '@/components/library'

createApp(App).use(store).use(router).use(UI).mount('#app')

image.png

引用组件

注意传递的变量不用使用“:”,因为接受的就是字符串类型。

<template v-if="data">
  XXXXXXXXXX
</template>
<!-- 没有属性或者尚未加载出来,就加载骨架组件 -->
<template v-else>
  <Skeleton height="18px" style="margin-right:5px" bg="rgba(255,255,255,0.2)" animated></Skeleton>
  <Skeleton class="skeleton" width="50px" height="18px" bg="rgba(255,255,255,0.2)"></Skeleton>
</template>