vue 实现懒加载
Vue 实现懒加载的方法
使用 v-lazy 指令(需安装插件)
安装 vue-lazyload 插件:
npm install vue-lazyload --save
在 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">
路由懒加载(动态导入)
通过动态 import() 语法实现路由组件懒加载:
const routes = [
{
path: '/home',
component: () => import('./views/Home.vue')
},
{
path: '/about',
component: () => import('./views/About.vue')
}
]
组件懒加载
使用 defineAsyncComponent 异步加载组件:
import { defineAsyncComponent } from 'vue'
const AsyncComponent = defineAsyncComponent(() =>
import('./components/AsyncComponent.vue')
)
export default {
components: {
AsyncComponent
}
}
图片懒加载(Intersection Observer API)
自定义指令实现原生懒加载:
const lazyLoad = {
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('lazy', lazyLoad)
// 使用指令
<img v-lazy="imageUrl" alt="Lazy Image">
懒加载占位策略
为懒加载元素添加加载状态:
<div v-if="isLoading">Loading...</div>
<img v-else v-lazy="imageUrl">
<script>
export default {
data() {
return {
isLoading: true
}
},
mounted() {
this.loadImage()
},
methods: {
loadImage() {
const img = new Image()
img.onload = () => {
this.isLoading = false
}
img.src = this.imageUrl
}
}
}
</script>
性能优化建议
- 设置合理的预加载阈值(如
preLoad: 1.3) - 提供高质量的占位图或加载动画
- 对移动端可降低图片质量要求
- 结合 WebP 等现代图片格式
- 使用 CDN 加速资源加载
以上方法可根据具体场景组合使用,路由懒加载适用于SPA应用,图片懒加载适合媒体资源密集页面。







