0
点赞
收藏
分享

微信扫一扫

wps卸载和重新安装

程序猿不脱发2 2023-11-18 阅读 41

一、使用Vue本身的指令

Vue本身提供了一个指令v-lazy,可以实现图片懒加载。使用方式如下:

<img v-lazy="imageSrc" />

其中,imageSrc是需要懒加载的图片路径。当图片进入可视区域时,Vue会自动加载图片。

二、使用第三方库(推荐)

2.1  安装下载

npm i vue-lazyload@1.2.3 -S

2.2  main.js 导入

import VueLazyload from 'vue-lazyload'

Vue.use(VueLazyLoad, {
  // 可选配置项,可省略
  error: require('./error.jpg'), // 加载失败时显示的图片
  loading: require('./loading.gif'), // 加载中时显示的图片
  preLoad: 1.3, // 预加载高度的比例
  attempt: 3 // 尝试加载次数
}) 

2.3  页面使用

<template>  
  <div>  
    <img v-lazy="imageSrc" />  
  </div>  
</template>  
  
<script>   
import Vue from 'vue'       // main.js 已引入的可忽略
import VueLazyload from 'vue-lazyload'  // main.js 已引入的可忽略
Vue.use(VueLazyload, {      // main.js 已引入的可忽略 
  // 配置项...  
})  
</script>


// 个人实操使用,可参考
<template>
  <div class="scroll-container">
    <div class="demo-image__lazy">
      <img v-for="(url, index) in imgUrl" :key="index" v-lazy="url" /> // 遍历图片
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        imgUrl: [  // 需要显示的所有图片
          require('@/assets/help/1.jpg'),
          require('@/assets/help/2.jpg'),
          require('@/assets/help/3.jpg'),
          require('@/assets/help/4.jpg'),
          require('@/assets/help/5.jpg'),
        ],
      }
    },
  }
</script>
<style lang="less" scoped> // 根据视口大小显示图片宽度
  @media screen and (max-width: 1200px) {
    .demo-image__lazy img {
      width: 100%;
    }
  }
  @media screen and (min-width: 1200px) {
    .demo-image__lazy img {
      width: 50%;
    }
  }
</style>

 三、自定义指令

<template>  
  <div>  
    <img v-lazyload="imageSrc" />  
  </div>  
</template>  
  
<script>  
export default {  
  directives: {  
    lazyload: {  
      inserted: function (el, binding) {  
        const observer = new IntersectionObserver(([entry]) => {  
          if (entry.isIntersecting) {  
            const img = new Image()  
            img.src = binding.value  
            el.appendChild(img)  
            observer.unobserve(el)  
          }  
        }, {threshold: 0.1})  
        observer.observe(el)  
      }  
    }  
  }  
}  
</script>
举报

相关推荐

0 条评论