一个实际应用中图片懒加载的过程

69 阅读1分钟

在一个页面中如果展示的图片的过多会出现加载变慢的情况,我们可以选择将没有展示在页面中的图片先不加载,当这个模块可见的时候在加载。

思路: 1.使用directive定义自定指令

2.使用vueuse的useIntersectionObserver这个Api

3.项目有多个模块需要使用懒加载,我们将自定义指令lazy注册成全局指令。

4.使用vue.use全局注册

5.在渲染图片的组件替代src

流程

一、创建组件 directive/index.ts

import { useIntersectionObserver } from "@vueuse/core"
import { App } from "vue"
import defaultImg from '@/assets/images/200.png'
export default {
  install(app: App) {
    app.directive('lazy', {
      mounted(el, binding) {
        // 设置默认图
        el.src =defaultImg
        console.log('lazy', el, binding)

        const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
          if (isIntersecting) {
            el.src = binding.value

            stop()
            // 如果图片加载失败,显示默认的图片
            el.onerror = function () {
              el.src = defaultImg
            }
          }
        })

      }
    })
  }
}

二、在mian.ts文件中注册挂载全局

import directive from './directives'
const app = createApp(App)
app.use(directive)

三、在对应组件中使用,将图片渲染的:src换成我们自定义指令lazy

<img
  v-lazy="item.picture" alt="" />

以上就是个图片懒加载的实现过程了