Vue 图片懒加载

225 阅读1分钟

一、自定义插件

main.js 中添加指令信息

image.png
// 定义全局指令
app.directive('img-lazy',{
    mounted(el,binding){
        // el: 指令绑定的元素 img
        // binding: binding.value 指定等于号后面绑定的表达式的值 图片url
        console.log(el)
        console.log(binding.value)
    }
})

测试:创建 img.vue 模拟要加载的图片,控制台成功打印图片信息,证明自定义指令添加成功

image.png
<template>
    <div v-for="(item,index) in imgList" :key="index">
        <img :src="item" v-img-lazy="item"/>
        <br/>
    </div>
</template>

<script setup>
    const imgList = ["/src/images/1.png","src/images/2.png","src/images/3.png","src/images/4.png","src/images/5.png","src/images/6.png"]
</script>

二、监控图片是否可视

工具类安装:npm i @vueuse/core

调用该工具类下判断可视的方法:

image.png

测试

根据图片是否可视,会在控制台打印对应的布尔信息

20231105_114318.gif

三、实现图片懒加载

image.png

修改原组件:

image.png

测试

20231105_131741.gif

四、指令优化

image.png

附:懒加载核心代码

// 定义懒加载插件
import { useIntersectionObserver } from '@vueuse/core'

export const lazyPlugin = {
  install (app) {
    // 懒加载指令逻辑
    app.directive('img-lazy', {
      mounted (el, binding) {
        // el: 指令绑定的那个元素 img
        // binding: binding.value  指令等于号后面绑定的表达式的值  图片url
        // console.log(el, binding.value)
        const { stop } = useIntersectionObserver(
          el,
          ([{ isIntersecting }]) => {
            console.log(isIntersecting)
            if (isIntersecting) {
              // 进入视口区域
              el.src = binding.value
              stop()
            }
          },
        )
      }
    })
  }
}