创建一个名为 lazy-load.js
的自定义指令文件:
const LazyLoadDirective = {
mounted(el, binding) {
const options = binding.value || {};
const { src, threshold = 0 } = options;
let observer;
function loadImage(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
el.src = src;
observer.unobserve(el);
}
});
}
observer = new IntersectionObserver(loadImage, {
rootMargin: `${threshold}px 0px`,
});
observer.observe(el);
},
};
export default LazyLoadDirective;
然后,在你的 Vue 应用中,全局注册这个自定义指令:
import { createApp } from 'vue';
import LazyLoadDirective from './directives/lazy-load';
const app = createApp(App);
app.directive('lazy-load', LazyLoadDirective);
app.mount('#app');
最后,在你的模板中使用这个自定义指令:
<img v-lazy-load="{ src: 'placeholder.jpg', threshold: 100 }" alt="Lazy Loaded Image">
这样,当图片进入视窗并达到指定的阈值时,它将开始加载真实的图片。