Vue3+Ts封装图片懒加载函数
定义懒加载Hook↓,IntersectionObserver 是浏览器原生提供的构造函数,接受两个参数:callback 是可见性变化时的回调函数,option 是配置对象。
1 interface IOptions { 2 threshold: number[] 3 root: HTMLElement 4 rootMargin: string 5 } 6 7 const useLazyImg = ( 8 root: HTMLElement, 9 img: HTMLImageElement, 10 options: IOptions = { 11 threshold: [0.5], 12 root: root, 13 rootMargin: '120px', 14 }, 15 ) => { 16 // start 17 function callbackFn(entries: any) { 18 if (entries[0].isIntersecting) { 19 img.src = img?.getAttribute('data-url') as string 20 io.unobserve(img as HTMLElement) 21 } 22 } 23 const io = new IntersectionObserver(callbackFn, options) 24 io.observe(img as HTMLElement) 25 // 卸载 26 function uninstall() { 27 io.disconnect() 28 } 29 30 return { uninstall } 31 } 32 33 export default useLazyImg
定义函数式ref获取到每个img元素↓(ref随便命名的)
1 <template> 2 <div class="category-list"> 3 <div :ref="divRef">category-list1</div> 4 <div :ref="divRef">category-list2</div> 5 <div :ref="divRef">category-list3</div> 6 </div> 7 </template> 8 9 <script setup lang="ts"> 10 import { ref } from 'vue' 11 12 const divRef = (e: any) => { 13 console.log(e) 14 } 15 </script>
循环生成数据时,给img标签加上:data-url属性并赋值所需图片url↓ 1 <img :data-url="contentsData?.data?.image?.url" alt="" :ref="divRef" />
到此即可开始监听图片是否到可视区并控制显示(observe方法的参数是一个 dom 节点,如果需要观察多个对象,则需要多次调用)

浙公网安备 33010602011771号