uniapp实现图片懒加载 封装组件

想要的效果就是窗口滑动到哪里,哪里的图片进行展示 主要原理使用IntersectionObserver

html 复制代码
<template>
  <view>
    <image @error="HandlerError" :style="imgStyle" :src="imageSrc" :id="randomId" :mode="mode" class="music-img" />
  </view>
</template>
<script setup lang="ts">
import { uuid } from '@/utils/index'

const instance = getCurrentInstance()
let observer2: any = null
const randomId = ref<string>('')
randomId.value = uuid()
type Props = {
  src: string
  loadingSrc: string
  imgStyle: any
  mode: string
  className: string
}
const props = defineProps<Props>()
let src = computed(() => {
  return props.src || ''
})
let loadingSrc = computed(() => {
  return props.loadingSrc || ''
})
let imgStyle = computed(() => {
  return props.imgStyle || { width: '200rpx' }
})
let mode = computed(() => {
  return props.mode || ''
})

let imageSrc = ref<string>('')

imageSrc.value = loadingSrc.value

const HandlerError = () => {}
onMounted(() => {
  if (imageSrc.value == loadingSrc.value) {
    // #ifdef APP || H5
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].intersectionRatio > 0) { //进入页面的占比>0 就认为要显示
          const img = entries[0].target
          imageSrc.value = src.value
          observer.unobserve(img)
        }
      },
      {
        root: null,
        rootMargin: '0px',
        threshold: 0.1
      }
    )
    const img: Element | null = document.getElementById(`${randomId.value}`)
    if (img) {
      observer.observe(img)
    }
    // #endif

    // #ifndef APP || H5
    observer2 = uni.createIntersectionObserver(instance).relativeToViewport()
    observer2.observe('.music-img', (res) => {
      if (res.intersectionRatio > 0) {
        imageSrc.value = src.value
      }
    })
    // #endif
  }
})
onUnmounted(() => {
  // #ifndef APP || H5
  if (observer2) {
    observer2.disconnect()
  }
  // #endif
})
</script>

<style></style>
相关推荐
江城开朗的豌豆6 小时前
React组件传值:轻松掌握React组件通信秘籍
前端·javascript·react.js
Sailing6 小时前
别再放任用户乱填 IP 了!一套前端 IP 与 CIDR 校验的高效方案
前端·javascript·面试
程序员爱钓鱼9 小时前
Go语言实战案例 — 项目实战篇:简易博客系统(支持评论)
前端·后端·go
excel16 小时前
ES6 中函数的双重调用方式:fn() 与 fn\...``
前端
可乐爱宅着16 小时前
全栈框架next.js入手指南
前端·next.js
你的人类朋友17 小时前
什么是API签名?
前端·后端·安全
会豪19 小时前
Electron-Vite (一)快速构建桌面应用
前端
中微子19 小时前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶19 小时前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子19 小时前
深入剖析 useState产生的 setState的完整执行流程
前端