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>
相关推荐
-凌凌漆-3 小时前
【vue】pinia中的值使用 v-model绑定出现[object Object]
javascript·vue.js·ecmascript
C澒3 小时前
前端整洁架构(Clean Architecture)实战解析:从理论到 Todo 项目落地
前端·架构·系统架构·前端框架
C澒3 小时前
Remesh 框架详解:基于 CQRS 的前端领域驱动设计方案
前端·架构·前端框架·状态模式
Charlie_lll3 小时前
学习Three.js–雪花
前端·three.js
onebyte8bits3 小时前
前端国际化(i18n)体系设计与工程化落地
前端·国际化·i18n·工程化
C澒4 小时前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC4 小时前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
0思必得04 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice4 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶3604 小时前
php怎么实现订单接口状态轮询(二)
前端·php·接口