安装VueUse
npm i @vueuse/core
需要使用到VueUse插件中 useIntersectionObserver 类似与监听元素是否出现于是视口
directives文件下index.js 封装的自定义指令
//定义懒加载插件
import { useIntersectionObserver } from "@vueuse/core";
export const lazyPlugin = {
install(app) {
//懒加载指令逻辑
app.directive("img-lazy", {
mounted(el, binding) {
//el:指令绑定的元素 img
//binding:binding.value 指令等于后面绑定的表达式的值 图片url
const { stop } = useIntersectionObserver(
el, //所需要监听的元素 isIntersecting监听的值 为布尔值
([{ isIntersecting }]) => {
//当达到视口区域
console.log(isIntersecting);
if (isIntersecting) {
el.src = binding.value; //就给el(img元素)的src 从新赋值也就是binding.value
stop(); //停止监听
}
}
);
},
});
},
};
main.js中
//引入懒加载指令插件注册
import { lazyPlugin } from "@/directives";
app.use(lazyPlugin);
HTML中使用
<img v-img-lazy="item.picture" alt="" />