vue实现懒加载的方法
vue实现懒加载的方法
使用Vue的<img>标签结合IntersectionObserver
在Vue组件中,通过IntersectionObserver监听图片是否进入视口,动态加载图片资源。这种方式适用于现代浏览器,性能较好。
<template>
<img v-lazy="imageUrl" alt="Lazy-loaded image">
</template>
<script>
export default {
directives: {
lazy: {
inserted(el, binding) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
el.src = binding.value;
observer.unobserve(el);
}
});
});
observer.observe(el);
}
}
},
data() {
return {
imageUrl: 'path/to/image.jpg'
};
}
};
</script>
使用第三方库vue-lazyload
vue-lazyload是一个流行的Vue懒加载插件,支持图片、背景图等资源的懒加载。安装后全局配置即可使用。
npm install vue-lazyload
在main.js中配置插件:

import VueLazyload from 'vue-lazyload';
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'path/to/error-image.png',
loading: 'path/to/loading-image.gif',
attempt: 3
});
在组件中使用:
<template>
<img v-lazy="imageUrl" alt="Lazy-loaded image">
</template>
路由懒加载
对于Vue Router的路由组件,可以使用动态import()语法实现懒加载,减少初始加载时间。

const routes = [
{
path: '/about',
component: () => import('./views/About.vue')
}
];
使用v-lazy指令结合自定义加载状态
可以自定义加载中和加载失败的占位图,提升用户体验。
<template>
<img v-lazy="imageUrl" :key="imageUrl" alt="Lazy-loaded image">
</template>
<script>
export default {
directives: {
lazy: {
inserted(el, binding) {
el.src = 'path/to/placeholder.png';
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = new Image();
img.src = binding.value;
img.onload = () => {
el.src = binding.value;
};
img.onerror = () => {
el.src = 'path/to/error.png';
};
observer.unobserve(el);
}
});
});
observer.observe(el);
}
}
}
};
</script>
使用loading="lazy"原生属性
现代浏览器支持loading="lazy"属性,简单实现图片懒加载,无需额外代码。
<template>
<img :src="imageUrl" loading="lazy" alt="Lazy-loaded image">
</template>
注意事项
IntersectionObserver不兼容IE,需使用polyfill。- 路由懒加载的组件会生成单独的chunk文件。
vue-lazyload支持更多高级功能,如延迟加载、重试机制等。- 原生
loading="lazy"属性兼容性需检查目标浏览器支持情况。






