目的: 当图片进入可视区域内去加载图片,且处理加载失败,封装成指令。
首先我们介绍一个webAPI:IntersectionObserver
// 创建观察对象实例
// const observer = new IntersectionObserver(callback[, options])
const obs = new IntersectionObserver(([{isIntersecting}], observer) => {
// entries = [{isIntersecting: true}]
}, {})
// 监听DOM元素
obs.observe(imgDom)
// 取消DOM监听
obs.unobserve(imgDom)
// callback 被观察dom进入可视区离开可视区都会触发
// - 两个回调参数 entries , observer
// - entries 被观察的元素信息对象的数组 [{元素信息},{}],信息中isIntersecting判断进入或离开
// - observer 就是观察实例
// options 配置参数
// - 三个配置属性 root rootMargin threshold
// - root 基于的滚动容器,默认是document
// - rootMargin 容器有没有外边距
// - threshold 交叉的比例
// 实例提供两个方法
// observe(dom) 观察哪个dom
// unobserve(dom) 停止观察那个dom
基于vue3.0和IntersectionObserver封装懒加载指令src/components/library/index.js
export default {
install (app) {
defineDirective(app)
}
}
import defaultImg from '@/assets/images/200.png'
// 指令
const defineDirective = (app) => {
// 图片懒加载指令
app.directive('lazyload', {
mounted (el, binding) {
const observer = new IntersectionObserver(([{ isIntersecting }]) => {
if (isIntersecting) {
observer.unobserve(el)
el.onerror = () => {
el.src = defaultImg
}
el.src = binding.value
}
}, {
threshold: 0.01
})
observer.observe(el)
}
})
}
使用指令:src/views/home/component/home-product.vue
<RouterLink class="cover" to="/">
<img alt="" v-lazyload="cate.picture">
<strong class="label">
<span>{{cate.name}}</span>
<span>{{cate.saleInfo}}</span>
</strong>
</RouterLink>
src/views/home/component/home-goods.vue
<RouterLink to="/" class="image">
<img alt="" v-lazyload="goods.picture" />
</RouterLink>
src/views/home/component/home-product.vue
<RouterLink class="cover" to="/">
<img v-lazyload="item.picture" alt="">
<strong class="label">
<span>{{item.name}}</span>
<span>{{item.saleInfo}}</span>
</strong>
</RouterLink>
注意: 在img上使用使用v-lazyload值为图片地址,不设置src属性。
- 原生js的API监听DOM元素进入可视区基本使用
- Vue3的自定义指令的基本规则
- 处理图片的加载和失败的情况