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>
相关推荐
Forfun_tt3 分钟前
xss-labs pass-12
前端·xss
云枫晖19 分钟前
Webpack系列-编译过程
前端·webpack
AskHarries28 分钟前
Toolhub — 一个干净实用的在线工具集合
前端·后端
H尗44 分钟前
Vue3响应式系统的精妙设计:深入理解 depsLength 与 trackId 的协同艺术
前端·vue.js
昔人'1 小时前
html`contenteditable`
前端·html
爱宇阳1 小时前
npm 常用标签与使用技巧新手教程
前端·npm·node.js
郑板桥301 小时前
TypeScript:npm的types、typings、@type的区别
javascript·typescript·npm
JinSoooo1 小时前
pnpm monorepo 联调:告别 --global 参数
开发语言·javascript·ecmascript·pnpm
@大迁世界1 小时前
2025 年该选谁?npm vs yarn vs pnpm
前端·npm·node.js
crary,记忆1 小时前
简介NPM 和 NPX
前端·学习·npm·node.js