木灵鱼儿

木灵鱼儿

阅读:1414

最后更新:2021/08/04/ 11:50:01

骨架动画指令 v-skeleton

意图

就是想图片在加载时,能显示骨架动画,然后图片加载完成,骨架动画消失。

这个可以用于一些小图的加载,比如:验证码、头像、logo啥的,如果是特别大的图,建议用懒加载

效果图

原理

  1. 指令在bind阶段,判断绑定的数据是否为trun,并且class类名不存在,添加一个class用于骨架背景动画
  2. 监听绑定值得变化,如果为false,那么移除class

那么如何判断图片是否加载完毕,可以使用@load事件

自定义指令

import "./scss/index.scss";

export default {
  //首次
  bind(el, binding) {
    if (!el.classList.contains("mu-skeleton-animated") && binding.value) {
      el.classList.add("mu-skeleton-animated")
    }
  },

  //更新
  update(el, binding) {
    if (el.classList.contains("mu-skeleton-animated") && !binding.value) {
      el.classList.remove("mu-skeleton-animated")
    }
  }
}

样式:

index.scss

//骨架动画
.mu-skeleton-animated {
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 37%, #f2f2f2 63%);
  background-size: 400% 100%;
  animation: mu-skeleton-loading 1.4s ease infinite;
}

@keyframes mu-skeleton-loading {
  0% {
    background-position: 100% 50%;
  }

  to {
    background-position: 0 50%;
  }
}

统一入口注册

import skeleton from "./lib/skeleton/index"


const directives = {
  skeleton
}


//批量注册
export default {
  install(Vue) {
    Object.keys(directives).forEach(key => {
      Vue.directive(key, directives[key]);
    })
  }
}

main.js文件引入

//自定义指令
import Directives from '@/base/directives'
Vue.use(Directives);

使用

<template>
  <div v-skeleton="loading">
     <img src="xxxx" @load="loading=false">
  </div>
</template>
<script>
  export default {
    data() {
      return {
        loading:true, //加载中
      }
    }
  }
</script>

版权申明

本文系作者 @木灵鱼儿 原创发布在木灵鱼儿 - 有梦就能远航站点。未经许可,禁止转载。

关于作者

站点职位 博主
获得点赞 2
文章被阅读 1414

相关文章