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>
相关推荐
努力学习的木子33 分钟前
uniapp如何隐藏默认的页面头部导航栏,uniapp开发小程序如何隐藏默认的页面头部导航栏
前端·小程序·uni-app
java小郭4 小时前
html的浮动作用详解
前端·html
水星记_4 小时前
echarts-wordcloud:打造个性化词云库
前端·vue
强迫老板HelloWord4 小时前
前端JS特效第22波:jQuery滑动手风琴内容切换特效
前端·javascript·jquery
luanluan88885 小时前
维护el-table列,循环生成el-table
javascript·vue.js·ecmascript·element plus
续亮~5 小时前
9、程序化创意
前端·javascript·人工智能
RainbowFish6 小时前
「Vue学习之路」—— vue的常用指令
前端·vue.js
Wang's Blog6 小时前
Webpack: 三种Chunk产物的打包逻辑
前端·webpack·node.js
pan_junbiao6 小时前
HTML5使用<blockquote>标签:段落缩进
前端·html·html5
38kcok9w2vHanx_6 小时前
从0开始搭建vue项目
前端·javascript·vue.js