目标:
1.当图片进入可视区域内才去加载图片
2.处理图片加载失败情况
3.封装成指令。
有一个原生API:IntersectionObserver
https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver
// 创建观察对象实例
const observer = new IntersectionObserver(callback[, options])
// 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
import defaultImg from '@/assets/images/default.png' //图片加载失败时候用的图片
export default {
install (app) {
defineDirective(app)//自定义指令
}
}
// 自定义指令
const defineDirective = (app) => {
// 1.图片懒加载指令v-lazyLoad
// 原理:先存储图片地址不能在src上,当图片进入可视区,将你存储图片地址设置给图片元素(dom)的src即可。
app.directive('lazyLoad', {
// vue2.0监听使用指令的DOM是否创建好,钩子函数: inserted
// vue3.0 的指令拥有的钩子函数和组件的一样,使用指令的DON是否创建好,钩子函数: mounted,onMounted是在组合API时候使用,现在是选项
mounted (el, binding) { // 绑定的元素,绑定的值
// 2.创建一个观察对象,来观察当前使用指令得元素
const observe = new IntersectionObserver(([{ isIntersecting }]) => {
if (isIntersecting) { // 如果进入了可视区
// 谁进入了可视区?得用observe去观察 是哪个元素使用了该指令,所以会传入dom对象el
// 停止观察,因为观察一次就够了
observe.unobserve(el)
// console.log(binding.value, el) // binding.value就是绑定的地址
// 3.监听图片加载失败,用默认图
el.onerror = () => {
el.src = defaultImg
}
// 4.将指令v-lazyLoad上的地址设置给el的src属性
el.src = binding.value
}
}, {
threshold: 0//进入到可视区交界就开始观察
})
observe.observe(el)// 使用observe上的observe方法观察这个dom元素
}
})
}
在main.js进行全局引入
import FN from './components/library'// 引入全局用的骨架屏插件
// 插件的使用,在main.js使用app.use(插件)
createApp(App).use(store).use(router).use(FN).mount('#app')
下面进行使用:
在随便一个带有图片的页面使用v-lazyLoad指令
<template>
<ul >
<li v-for="item in goods" :key="item.id">
<!-- <img :src="item.picture" alt=""> --> 原本的写法
<img v-lazyLoad="item.picture" alt=""> 使用图片懒加载指令
</li>
</ul>
</template>