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 小时前
Android Gradle 学习 - Kts Gradle学习
前端·gradle
祈澈菇凉6 小时前
Next.js 零基础开发博客后台管理系统教程(八):提升用户体验 - 表单状态、加载与基础验证
前端·javascript·ux
有意义6 小时前
从日常使用到代码实现:B 站签名编辑的 OOP 封装思路与实践
javascript·代码规范·ecmascript 6
nvd116 小时前
SSE 流式输出与 Markdown 渲染实现详解
javascript·python
电商API大数据接口开发Cris6 小时前
淘宝 API 关键词搜索接口深度解析:请求参数、签名机制与性能优化
前端·数据挖掘·api
小周同学6 小时前
vue3 上传文件,图片,视频组件
前端·vue.js
细心细心再细心6 小时前
runtime-dom记录备忘
前端
小猪努力学前端6 小时前
基于PixiJS的小游戏广告开发
前端·webgl·游戏开发
哆啦A梦15886 小时前
62 对接支付宝沙箱
前端·javascript·vue.js·node.js