vue 实现懒加载
Vue 实现懒加载的方法
使用 Vue 的异步组件
Vue 允许将组件定义为异步加载的工厂函数,通过动态导入语法实现懒加载。
const AsyncComponent = () => import('./AsyncComponent.vue')
在路由配置中使用异步组件:
const router = new VueRouter({
routes: [
{ path: '/async', component: () => import('./AsyncComponent.vue') }
]
})
使用 Vue Router 的懒加载
Vue Router 支持路由级别的懒加载,通过动态导入语法分割代码块。

const router = new VueRouter({
routes: [
{ path: '/home', component: () => import('./views/Home.vue') },
{ path: '/about', component: () => import('./views/About.vue') }
]
})
使用 v-lazy 指令实现图片懒加载
安装 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 image">
使用 Intersection Observer API
自定义指令实现懒加载:
Vue.directive('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)
}
})
使用方式:
<img v-lazy="imageUrl" alt="lazy image">
第三方库推荐
vue-lazyload:轻量级的图片懒加载插件@vueuse/core:提供useIntersectionObserver等组合式 APIvue-lazy-hydration:针对 SSR 的组件级懒加载方案
每种方法适用于不同场景,异步组件适合路由和组件分割,图片懒加载优化媒体资源加载,Intersection Observer 提供更灵活的懒加载控制。






