vue自定义指令实现图片懒加载
我们使用的是vueuse中的useIntersectionObserver实现,vueuse官网链接
- 安装vueuse
npm i @vueuse/core
-
在vue项目中,src目录下,新建一个directives文件夹,新建一个index.js文件。
-
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
// 解构stop方法
const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
if (isIntersecting) {
// 进入视口区域
el.src = binding.value;
// 加载后调用stop方法,防止重复,浪费资源
stop();
}
});
},
});
},
};
- 在mian.js中引入并挂载到全局
import { createApp } from 'vue'
import App from './App.vue'
// 引入懒加载指令插件
import { lazyPlugin } from '@/directives'
const app = createApp(App)
//注册
app.use(lazyPlugin)
app.mount('#app')
- 项目中使用
<img v-img-lazy="图片地址" alt="">