使用 vue-lazyload 实现图片懒加载

163 阅读1分钟
第一步:安装 vue-lazyload。版本不要超过 2.0,否则库无法成功注册自定义指令 z-lazy 。
yarn add vue-lazyload@1.3.3
第二步:在 main.js 中引入和全局注册
import VueLazyload from "vue-lazyload";

const loadimage = require("./assets/loading.png");
const errorimage = require("./assets/error.png");

Vue.use(VueLazyload, {
  preLoad: 1.3,  // 预加载高度
  error: errorimage,  // 报错时的显示图片
  loading: loadimage,  // 加载时的显示图片
  attempt: 1,  // 图片尝试加载次数
});
第三步:在组件中直接使用,这里为 Test.vue。如果是本地图片,且图片放在 assets 文件中时,需要使用 require 引入图片(因为 webpack 编译的原因,直接使用相对路径无法引入),且 require 接受的参数只能为 path 类型,不能为字符串,如果 src 是字符串,要使用拼接或模板字符串的方式来引入。

path 类型:参考文章1

path 类型:参考文章2

<template>
  <div class="img">
    <div v-for="(img,index) in list" :key="index">
      <img v-lazy='img' />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return { list: [] }
  },
  created() {
    const pathName = 'picture.png'
    for (let i = 0; i < 50; i++) {
      this.list.push(require("../assets/" + pathName))
    }
  }
}
</script>

<style lang="scss" scoped>
.img {
  width: 100%;
  div {
    display: flex;
    justify-content: center;
    img {
      width: 50%;
      margin: 20px 0;
    }
  }
}
</style>