vue实现延迟加载
Vue 实现延迟加载的方法
使用 v-lazy 指令(需安装插件)
安装 vue-lazyload 插件:
npm install vue-lazyload --save
在 main.js 中配置:
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
loading: 'path/to/loading-spinner.gif',
error: 'path/to/error-image.png',
attempt: 3
})
模板中使用:
<img v-lazy="imageUrl" alt="description">
路由懒加载(动态导入)
通过动态 import() 语法实现路由组件按需加载:
const routes = [
{
path: '/about',
component: () => import('./views/About.vue')
}
]
组件懒加载
使用 defineAsyncComponent(Vue 3):
import { defineAsyncComponent } from 'vue'
const AsyncComponent = defineAsyncComponent(() =>
import('./components/MyComponent.vue')
)
Vue 2 写法:
components: {
MyComponent: () => import('./MyComponent.vue')
}
图片懒加载(原生 IntersectionObserver 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">
条件渲染结合定时器
通过 v-if 和 setTimeout 延迟渲染:
<div v-if="showComponent">
<heavy-component />
</div>
data() {
return { showComponent: false }
},
mounted() {
setTimeout(() => {
this.showComponent = true
}, 2000)
}
注意事项
- 图片懒加载需设置默认占位图避免布局抖动
- 路由懒加载会产生独立 chunk 文件
- 移动端注意 IntersectionObserver 的兼容性
- 服务端渲染(SSR)场景需特殊处理懒加载逻辑







