Vue实现lagger页面
Vue实现懒加载页面的方法
懒加载(Lazy Loading)是一种优化技术,用于延迟加载页面或组件,直到它们真正需要显示时才加载。以下是几种在Vue中实现懒加载页面的常见方法:
使用Vue Router的懒加载
Vue Router原生支持懒加载路由组件,通过动态导入语法实现:
const routes = [
{
path: '/lazy-page',
component: () => import('./views/LazyPage.vue')
}
]
这种方式会在访问/lazy-page路由时才加载对应的组件代码。
组件级别的懒加载
对于非路由组件,可以使用Vue的defineAsyncComponent实现懒加载:
import { defineAsyncComponent } from 'vue'
const LazyComponent = defineAsyncComponent(() =>
import('./components/LazyComponent.vue')
)
然后在模板中像普通组件一样使用:
<template>
<LazyComponent v-if="showComponent" />
</template>
图片懒加载
对于图片资源,可以使用vue-lazyload库:

安装依赖:
npm install vue-lazyload
使用方式:
import VueLazyload from 'vue-lazyload'
app.use(VueLazyload, {
preLoad: 1.3,
error: 'error.png',
loading: 'loading.gif',
attempt: 1
})
模板中使用v-lazy指令:

<img v-lazy="imageUrl">
基于Intersection Observer的懒加载
对于自定义懒加载需求,可以使用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 loaded image">
条件渲染结合懒加载
对于复杂场景,可以结合v-if和动态导入:
const showComponent = ref(false)
const LazyComponent = shallowRef(null)
const loadComponent = async () => {
LazyComponent.value = (await import('./HeavyComponent.vue')).default
showComponent.value = true
}
模板中:
<button @click="loadComponent">Load</button>
<component :is="LazyComponent" v-if="showComponent" />
这些方法可以根据具体需求选择使用或组合使用,有效提升页面初始加载性能。






