vue实现 懒加载
实现图片懒加载
在Vue中实现图片懒加载可以通过IntersectionObserver API或第三方库如vue-lazyload完成。以下是两种方法的实现方式:
使用IntersectionObserver API
<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: 'https://example.com/image.jpg'
}
}
}
</script>
使用vue-lazyload库 安装库:
npm install vue-lazyload
在main.js中配置:

import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'error.png',
loading: 'loading.gif',
attempt: 1
})
组件中使用:
<img v-lazy="imageUrl" alt="Lazy loaded image">
实现路由懒加载
Vue Router支持动态导入语法实现路由级组件懒加载,能有效减少初始加载体积:

基本用法
const router = new VueRouter({
routes: [
{
path: '/about',
component: () => import('./views/About.vue')
}
]
})
分组打包 使用webpack的魔法注释可将组件分组打包:
const About = () => import(/* webpackChunkName: "group-about" */ './views/About.vue')
const Contact = () => import(/* webpackChunkName: "group-about" */ './views/Contact.vue')
组件懒加载
对于非路由组件,可使用动态导入配合<component>实现按需加载:
<template>
<button @click="loadComponent">Load</button>
<component :is="dynamicComponent"/>
</template>
<script>
export default {
data() {
return {
dynamicComponent: null
}
},
methods: {
async loadComponent() {
this.dynamicComponent = await import('./HeavyComponent.vue')
}
}
}
</script>
注意事项
- 图片懒加载应考虑占位图避免布局偏移
- 路由懒加载需配合webpack等打包工具使用
- 动态导入的组件需处理加载状态和错误状态
- 移动端可适当增大IntersectionObserver的rootMargin提前加载
- 生产环境应配置合适的代码分割策略
以上方法可根据实际需求组合使用,显著提升页面加载性能。






