基于vue2的图片懒加载

基于vue2的图片懒加载

1. 使用vue-lazyload库

npm install vue-lazyload --save
  • 在main.js里面进行注册
import Vue from 'vue'
import VueLazyLoad from 'vue-lazy-load'
Vue.use(VueLazyLoad,{
    
    
    preLoad:1.3,
    error:'dist/xx.png',
    loading:'dist/yy.png',
    attempt:1
})
  • 然后在组件中使用v-lazy指令绑定src
<template>
  <div class="home">
    <h1>图片懒加载</h1>
    <div v-for="(item, index) in list" :key="index">
      <img v-lazy="item.src" style="height: 420px; width: 420px" alt="" />
    </div>
  </div>
</template>

<script>
export default {
  name: "home",
  data() {
    return {
      list: [
        {
          src: "https://img0.baidu.com/it/u=394333074,1787648005&fm=253&fmt=auto&app=138&f=JPEG?w=636&h=500",
        },
        {
          src: "https://img2.baidu.com/it/u=683632201,378173214&fm=253&fmt=auto&app=138&f=JPG?w=1118&h=410",
        },
        {
          src: "https://img1.baidu.com/it/u=945585991,3392397995&fm=253&fmt=auto&app=138&f=JPEG?w=605&h=500",
        },
        {
          src: "https://img2.baidu.com/it/u=2751893563,239775612&fm=253&fmt=auto&app=138&f=PNG?w=622&h=500",
        },
        {
          src: "https://img2.baidu.com/it/u=2933650591,4207845479&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=501",
        },
      ],
    };
  },
};
</script>