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>
相关推荐
前端小咸鱼一条22 分钟前
React组件化的封装
前端·javascript·react.js
随便起的名字也被占用30 分钟前
leaflet中绘制轨迹线的大量轨迹点,解决大量 marker 绑定 tooltip 同时显示导致的性能问题
前端·javascript·vue.js·leaflet
南方kenny36 分钟前
TypeScript + React:让前端开发更可靠的黄金组合
前端·react.js·typescript
2501_9159184136 分钟前
iOS 抓不到包怎么办?全流程排查思路与替代引导
android·ios·小程序·https·uni-app·iphone·webview
Cache技术分享39 分钟前
149. Java Lambda 表达式 - Lambda 表达式的序列化
前端·后端
LaoZhangAI1 小时前
GPT-5推理能力全解析:o3架构、链式思考与2025年8月发布
前端·后端
HebyH_1 小时前
uniapp如何封装uni.request 全局使用
uni-app
JuneXcy1 小时前
11.Layout-Pinia优化重复请求
前端·javascript·css
子洋1 小时前
快速目录跳转工具 zoxide 使用指南
前端·后端·shell
天下无贼!1 小时前
【自制组件库】从零到一实现属于自己的 Vue3 组件库!!!
前端·javascript·vue.js·ui·架构·scss