Vue实现lagger页面
Vue 实现懒加载页面
懒加载(Lazy Loading)是一种优化技术,用于延迟加载非关键资源,从而提升页面初始加载速度。在 Vue 中可以通过路由懒加载和组件懒加载实现。
路由懒加载
通过动态导入语法实现路由懒加载,Vue Router 会自动将组件拆分为单独的代码块,仅在访问对应路由时加载。
const routes = [
{
path: '/lazy-page',
component: () => import('./views/LazyPage.vue') // 动态导入
}
]
组件懒加载
使用 defineAsyncComponent 或动态导入实现组件懒加载,适合大型组件。
import { defineAsyncComponent } from 'vue'
const LazyComponent = defineAsyncComponent(() =>
import('./components/LazyComponent.vue')
)
图片懒加载
通过 IntersectionObserver API 或第三方库(如 vue-lazyload)实现图片懒加载。
安装 vue-lazyload:
npm install vue-lazyload
配置插件:
import VueLazyload from 'vue-lazyload'
app.use(VueLazyload, {
preLoad: 1.3,
loading: 'placeholder.png',
error: 'error.png'
})
使用方式:
<img v-lazy="imageUrl" />
指令实现懒加载
自定义指令结合 IntersectionObserver 实现元素懒加载。
const lazyLoadDirective = {
mounted(el, binding) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
el.src = binding.value
observer.unobserve(el)
}
})
})
observer.observe(el)
}
}
app.directive('lazyload', lazyLoadDirective)
使用方式:

<img v-lazyload="imageUrl" />
注意事项
- 懒加载可能影响 SEO,需确保关键内容优先加载。
- 测试不同网络环境下的加载表现。
- 合理设置预加载阈值(如
preLoad参数)平衡用户体验。
以上方法可根据实际需求组合使用,实现更精细的懒加载策略。






