Vue自定义指令实现图片懒加载
其实实现懒加载的方式有很多了,现在也有很多插件(比如:vue-lazyload等),element-ui库中也有图片懒加载的方式,所以大家根据自己的喜欢选择就可以了
IntersectionObserver
首先要用到这么个API,直接可以用的哈,它可以很方便的帮我们监视某个dom元素是否出现在可视区域内
使用起来也很方便
// 观察者
const observer = new IntersectionObserver(([{ isIntersecting }]) => {
// 如果元素出现在可视区域内,和离开可视区域的时候被触发
if(isIntersecting) {
}
})
// 开启观察(传入要观察的dom元素)
observer.observe(el)
这是其中的一些方法
下面介绍Vue中自定义指令实现懒加载:
可以在src下新建directive/index.js
import Vue from 'vue'
// 图片懒加载
Vue.directive('lazy', {
inserted(el) {
const imgSrc = el.src
el.src = ''
// 观察者
const observer = new IntersectionObserver(([{ isIntersecting }]) => {
// 如果元素出现在可视区域内,和离开可视区域的时候被触发
if(isIntersecting) {
// 出现在可视区域,再加载图片
el.src = imgSrc
// 停止观察
observer.unobserve(el)
}
})
// 开启观察(传入要观察的dom元素)
observer.observe(el)
}
})
import './directive'
<template>
<div class="home">
<!-- 模拟滚动 -->
<div style="height: 1000px;"></div>
<!-- 三张图片懒加载 -->
<div v-for="item in 3" :key="item">
<img v-lazy :src="require(`../assets/${ item }.png`)" alt="">
</div>
</div>
</template>