一、图片懒加载
1. src下创建目录directives/index.ts
import { useIntersectionObserver } from "@vueuse/core";
// 默认图片
import defaultImg from "@/assets/images/200.png";
import { App } from "vue";
export default {
install(app: App) {
app.directive("lazy", {
mounted(el, binding) {
const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
// isIntersecting 用于判断el元素是否进入可视区
if (isIntersecting) {
el.src = binding.value;
// 错误回调 显示默认图片
el.onerror = function () {
this.src = defaultImg;
};
stop();
}
});
},
});
},
};
2. 页面中使用
<img v-lazy="item.picture" alt="" />
二、数据懒加载
1. src下创建目录hooks/index.ts
import { useIntersectionObserver } from "@vueuse/core";
import { ref } from "vue";
export const useLazyLoad = (callback: () => void) => {
const target = ref(null);
const { stop } = useIntersectionObserver(target, ([{ isIntersecting }]) => {
if (isIntersecting) {
callback();
stop();
}
});
return target;
};
2. 页面中使用
<script lang="ts" setup name="HomeHot">
import { useLazyLoad } from "@/hooks";
//调用懒加载方法,ref="target"的元素到达可视区时会执行home.getHotGoodsList()函数
const target = useLazyLoad(home.getHotGoodsList);
</script>
<template>
<div>
<!-- ref="target"的元素会懒加载 -->
<HomePanel title="人气推荐" sub-title="人气爆款 不容错过" ref="target">
</HomePanel>
</div>
</template>