1.vue3自定义指令图片懒加载
效果:当滚动到可视区域图片加载
步骤:
1)注册全局自定义指令
2)获取可视区域,当可视区域为true是,el.src=binding.value
当加载失败时,el.src=默认的加载图片
3)给Dom绑定自定义指令
1 /** 2 * vue插件:注册全局指令 3 */ 4 // 导入监控方法 5 import { useIntersectionObserver } from '@vueuse/core' 6 import Def from '@/assets/images/load.gif' 7 export default { 8 install (app) { 9 console.log('指令:', app) 10 app.directive('imglazy', { 11 // vue2: inserted → vue3:mounted 12 /** 13 * 14 * @param {*} el img的dom对象 15 * @param {*} binding.value 指令绑定的图片地址 16 */ 17 mounted (el, binding) { 18 // console.log('执行:', el, binding) 19 const { stop } = useIntersectionObserver( 20 el, 21 ([{ isIntersecting }]) => { 22 // console.log('监控回调函数:', isIntersecting) 23 if (isIntersecting) { 24 el.src = Def 25 // console.log('进入可视区了,发请求') 26 // 看效果,可以延时(实际开发不要加) 27 setTimeout(() => { 28 el.src = binding.value 29 }, 2000) 30 // 加载失败 31 el.onerror = () => { 32 // 图片加载失败,显示默认图片 33 el.src = Def 34 } 35 // 关闭监控 36 stop() 37 } 38 }, 39 { 40 threshold: 0 // 进入后立马触发 41 } 42 ) 43 } 44 }) 45 } 46 }

浙公网安备 33010602011771号