【Vue3】 vue3图片懒加载-封装自定义指令

图片懒加载-介绍

目标:了解如何实现数据懒加载

电商类网站,图片会非常的多,而如果一上来就加载所有的图片,会导致网页加载很慢。

图片懒加载:等图片正式进入到可视区中时,才加载对应的图片,否则不请求图片

问题

如何知道图片进入或者离开了可视区?

  1. 通过vueuse封装的useIntersectionObserver

核心代码:

(1)useIntersectionObserver的基本使用

<script lang="ts" setup>
import {
    
     useIntersectionObserver } from '@vueuse/core'
import {
    
     ref } from 'vue'
const target = ref<HTMLImageElement | null>(null)
// stop停止监听
const {
    
     stop } = useIntersectionObserver(target, ([{
    
     isIntersecting }]) => {
    
    
  console.log('执行了')
  console.log(isIntersecting)

  if (isIntersecting) {
    
    
    target.value!.src =
      'https://yanxuan-item.nosdn.127.net/79f289a4e975fd030d5c37b98b9282c5.jpg'
    stop()
  }
})
</script>

<template>
  <div style="height: 3000px"></div>
  <img ref="target" alt="" />
</template>

<style scoed lang="less"></style>

图片懒加载-封装自定义指令

目标:自己封装指令 v-lazy,实现图片懒加载

新建 directives/index.ts

核心代码

import {
    
     App } from 'vue'
import Skeleton from './Skeleton/index.vue'
import Slider from './Slider/index.vue'
import More from './More/index.vue'
import {
    
     useIntersectionObserver } from '@vueuse/core'
import defaultImg from '@/assets/images/200.png'
export default {
    
    
  install(app: App) {
    
    
    // 全局注册组件
    app.component('Skeleton', Skeleton)
    app.component('Slider', Slider)
    app.component('More', More)

    // 自定义指令
    // <img :src="item.src" alt="" />
    // <img v-lazy="item.src" alt="" />
    app.directive('lazy', {
    
    
      mounted(el: HTMLImageElement, {
    
     value }) {
    
    
        // 图片的懒加载逻辑
        // 参数1:回调函数
        // 参数2:可选的配置
        const {
    
     stop } = useIntersectionObserver(el, ([{
    
     isIntersecting }]) => {
    
    
          if (isIntersecting) {
    
    
            // 停止监听
            stop()
            // 给el元素设置src属性
            // value = '123.jpg'
            el.src = value
            // 如果图片加载失败,显示默认的图片
            el.onerror = function () {
    
    
              el.src =  defaultImg
            }
          }
        })
      }
    })
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_46862327/article/details/129035539