一、介绍
懒加载(Load On Demand)——也称为延迟加载,它能够在用户滚动页面的时候自动获取更多的数据,而新得到的数据不会影响原有数据的显示,同时最大程度上减少服务器端的资源耗用。其关键就是,在图片没有进入可视区域时,先不给的src赋值,这样浏览器就不会发送请求了,等到图片进入可视区域再给src赋值。
二、自定义指令
vue3.0写法
1、安装插件
yarn add @vueuse/core -S
2、创建lazy-image.js文件(名称自己取)
3、编写实现代码如下
import { useIntersectionObserver } from '@vueuse/core'
export default {
install(app) {
app.directive('lazy', {
mounted(el, binding) {
el.src = 'https://img1.halobear.com/upload_page/FttW92R6o7V11_tP9RTUiDv6vlBL.png' // 默认图片(占位图)
const { stop } = useIntersectionObserver(
el,
([{ isIntersecting }]) => {
if (isIntersecting) {
// 可见区域
el.onerror = () => {
// 当图片加载失败 设置为默认图片
el.src = 'https://img1.halobear.com/upload_page/FttW92R6o7V11_tP9RTUiDv6vlBL.png'
}
el.setAttribute('class', 'fadeIn cover') // 给元素添加自定义class
stop() // 可见区域后 下次不在执行监听
el.src = binding.value // 设置传过来的地址去请求
}
},
{ threshold: 0 }
) // 当可视区域宽高为0就触发
// console.log(el, binding.value)
}
})
}
}
4、在main.js中引入
import directive from '@/common/waterfall/lazy-image
createApp(App).use(router).use(directive).mount('#app')
三、使用方法
<img class="cover"
:key="it.thumb_path"
src="https://img1.halobear.com/upload_page/FttW92R6o7V11_tP9RTUiDv6vlBL.png"
v-lazy="it.thumb_path"
:style="{ height: `${it.imageHeight}rem` }"
/>
四、实现效果
网络差的情况下也会显示占位图。