今天我们使用原始js实现图片的懒加载,利用自定义指令以及原生的方法IntersectionObserver 构造函数 来实现图片的懒加载功能
首先,我们先来介绍一下原生的IntersectionObserver 方法
// 创建观察对象实例
new一个实例
const observer = new IntersectionObserver(callback[, options])
const obs = new IntersectionObserver((entries, observer) => {
// entries = [{isIntersecting: true}]
}, {})
监听DOM(参数就是要监听的dom)
obs.observe(imgDom)
取消监听
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
具体步骤:
1、监听图片进去可视区
2、封装一个自定义指令
3、使用自定义指令,直接操作图片,给他的src属性赋值
我们在自定义插件中封装一个自定义指令
// UI组件库插件
// Vue插件的本质是对象对象中必须提供insall,()
import defaultImg from '@/assets/images/200.png'
export default {
install(app) {
// 扩展一个自定义指令
app.directive('lazyload', {
// vue2规则:使用inserted
// inserted(){}
// vue3使用mounted
mounted(el, binding) {
// el表示使用指令的dom元素
// binding表示指令相关的信息 bindings.value表示指令的值
// 指令的功能:实现图片的懒加载
// 1、监听图片进去可视区
const observer = new IntersectionObserver(([{ isIntersecting }]) => {
if (isIntersecting) {
// 进入可视区
// 2、给图片的src属性赋值图片的地址
el.src = binding.value
// 数据加载完取消图片的监听
observer.unobserve(el)
// 加载的图片失败了,显示默认的图片地址
el.onerror = () => {
el.src = defaultImg
}
}
})
observer.observe(el)
}
})
}
}
在main.js注册这个插件
import router from './router'
import store from './store'
import XxxUI from '@/components/library/index.js'
createApp(App)
.use(store)
.use(router)
.use(XxxUI)
.mount('#app')
这样就可以直接使用这个自定义指令啦
使用方式:直接操作图片,给图片的src属性赋值
eg:
<img v-lazyload="item.picture" alt="" />
小伙伴们,这样一个使用原生js封装的自定义指令就封装好了,快去用起来把