vue3+ts的项目中实现骨架屏

一、src/components下新建目录 skeleton/index.vue 

骨架屏本质上就是一个div元素,给它设置宽高背景色 动画等.. 就能得到不一样的骨架屏样式

<script setup lang="ts" name="XtxSkeleton">
defineProps({
  bg: {
    type: String,
    default: "#efefef",
  },
  width: {
    type: Number,
    required: true,
  },
  height: {
    type: Number,
    required: true,
  },
  animated: {
    type: Boolean,
    default: false,
  },
  fade: {
    type: Boolean,
    default: false,
  },
});
</script>

<template>
  <div
    class="xtx-skeleton"
    :style="{
      width: width + 'px',
      height: height + 'px',
    }"
    :class="{
      shan: animated,
      fade,
    }"
  >
    <!-- 盒子-->
    <div
      class="block"
      :style="{
        backgroundColor: bg,
      }"
    ></div>
  </div>
</template>

<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%;
  }
}

.fade {
  animation: fade 1s linear infinite alternate;
}
@keyframes fade {
  from {
    opacity: 0.2;
  }
  to {
    opacity: 1;
  }
}
</style>

二、骨架屏注册成全局组件

// 统一的注册所有的全局组件

// 骨架屏组件
import XtxSkeleton from '@/components/skeleton/index.vue'
import { App } from 'vue'
export default {
    install(app: App) {
        app.component(XtxSkeleton.name, XtxSkeleton)
    },
}

三、main.ts注册成全局插件

// 导入全局组件 ,挂载到App上
import XtxUI from './components'
createApp(App).use(XtxUI).use(router).use(createPinia()).mount('#app')

 四、页面中使用

<script setup lang="ts">
import { ref } from "vue";
const list = ref([]);
</script>
<template>
  <div>
    <!-- 如果list数据存在,渲染数据 -->
    <template v-if="list">
      <!-- 数据渲染 -->
    </template>
    <!-- 否则渲染骨架屏 -->
    <template v-else>
      <XtxSkeleton
        :width="60"
        :height="18"
        style="margin-right: 5px"
        bg="rgba(255,255,255,0.2)"
        animated
      />
      <XtxSkeleton
        :width="50"
        :height="18"
        bg="rgba(255,255,255,0.2)"
        animated
      />
    </template>
  </div>
</template>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值