目的:当图片进入可视区域的时候去加载图片,且数据要是加载失败,会显示默认的图片
需解决的问题:
1.如果监听图片进入可视区域
2.直接操作图片,给他的src属性赋值
3.自定义指令的规则
自定义指令实现如下的
src\components\library\index.js
注意:使用webapi:IntersectionObserve ,vueuse中的useIntersectionObserve的底层就是由这个webAPI而来的
其中有两个方法 observe.observe(imgDom) //检测哪个dom元素
observe.unobserve(imgDom) //停止检测哪个dom元素
// ui组件库插件
// vue插件的本质是对象(对象中必须提供install方法)
import XtxSkeleton from './xtx-skeleton.vue'
import XtxCarousel from './xtx-carousel.vue'
import XtxMore from './xtx-more.vue'
import defaultImg from '@/assets/200.png'
export default {
// vue2中install中的参数是Vue是vue构造函数,vue3中是app是根组件的实例对象
install(app) {
// 配置一个全局组件
app.component(XtxSkeleton.name, XtxSkeleton)
app.component(XtxCarousel.name, XtxCarousel)
app.component(XtxMore.name, XtxMore)
// 扩展自定义指令
app.directive('lazyload', {
// Vue2规则:instered
// Vu3自定义指令使用mounted
mounted(el, bindings) {
// el表示使用指令的dom元素 bingings表示指令相关的信息 值:bingings.value
// 指令的功能是实现图片的懒加载
// 1.监听图片进入可视区域
const observer = new IntersectionObserver(([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = bindings.value
// isIntersecting为真之后停止监测
observer.unobserve(el)
// 如果加载的数据失败了,使用默认的图片
el.onerr = () => {
el.src = defaultImg
}
}
},{
threshold:0 // 门槛 交集处 默认>0 如果图片较多会有空白区域,所以需要设置为0 取值是0-1之间
}
)
observer.observe(el)
// 2.给图片的src属性赋值图片的地址
}
})
}
}
小bug:图片多的时候会有刷新会有空白区域,设置threshold属性即可
使用:(将src换为v-lazyload 就算src前面有:也是好使的)
<RouterLink class="cover" to="/">
+ <img v-lazyload="item.picture" alt="">
<strong class="label">
<span>{{item.name}}馆</span>
<span>{{item.saleInfo}}</span>
</strong>
</RouterLink>
祝看到我微博的人拥有快乐的一天~拜