实现效果:
实现步骤:
1.封装自定义指令:
import { App, DirectiveBinding } from 'vue';
const install = (app: App) => {
app.directive('lazy-load', {
mounted(el: HTMLImageElement, binding: DirectiveBinding) {
const options = {
root: null, // 默认根元素是视窗
rootMargin: '0px',
threshold: 0.1, // 元素可见度达到10%时触发回调
};
const callback: IntersectionObserverCallback = (
entries: IntersectionObserverEntry[],
observer: IntersectionObserver
) => {
entries.forEach((entry: IntersectionObserverEntry) => {
if (entry.isIntersecting) {
// 模拟图片加载
setTimeout(() => {
el.src = binding.value; // 设置图片的src属性为绑定的值
observer.unobserve(el); // 停止观察该元素
}, 1000);
}
});
};
const observer = new IntersectionObserver(callback, options);
observer.observe(el);
},
});
};
export default install;
2.进行全局引入:
在main.ts中进行全局引入
import install from "./dirctive";
app.use(install)
3.属性替换
在页面组件中将src属性替换为我们的自定义指令
<img v-lazy-load="item.imgs" alt="">