当前位置:首页 > VUE

vue懒加载实现方式

2026-02-21 08:45:08VUE

Vue 懒加载实现方式

路由懒加载

通过动态导入语法实现路由组件按需加载,减少首屏加载时间。

const routes = [
  {
    path: '/home',
    component: () => import('./views/Home.vue')
  },
  {
    path: '/about',
    component: () => import('./views/About.vue')
  }
]

Webpack 会将动态导入的组件打包成单独的文件,在访问对应路由时才会加载。

组件懒加载

使用 Vue 的 defineAsyncComponent 方法实现组件懒加载。

import { defineAsyncComponent } from 'vue'

const AsyncComponent = defineAsyncComponent(() =>
  import('./components/AsyncComponent.vue')
)

在模板中像普通组件一样使用:

<template>
  <AsyncComponent />
</template>

图片懒加载

通过 v-lazy 指令或 Intersection Observer API 实现图片懒加载。

vue懒加载实现方式

使用 vue-lazyload 插件:

import VueLazyload from 'vue-lazyload'

Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'error.png',
  loading: 'loading.gif',
  attempt: 1
})

在模板中使用:

<img v-lazy="imageUrl" />

懒加载指令

自定义懒加载指令,基于 Intersection Observer API。

vue懒加载实现方式

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">

懒加载库

使用第三方库如 lozad.js 实现更复杂的懒加载需求。

import lozad from 'lozad'

const observer = lozad('.lazy', {
  loaded: function(el) {
    el.classList.add('loaded')
  }
})
observer.observe()

HTML 中使用:

<img class="lazy" data-src="image.jpg">

注意事项

  • 懒加载可能影响 SEO,需确保搜索引擎能正确抓取内容
  • 考虑设置合理的预加载区域,避免用户等待
  • 对关键内容谨慎使用懒加载,保证用户体验
  • 移动端网络环境较差时,懒加载效果更明显

以上方法可根据实际需求组合使用,平衡性能和用户体验。

标签: 加载方式
分享给朋友:

相关文章

加载jquery

加载jquery

加载 jQuery 的方法 通过 CDN 加载 推荐使用官方或公共 CDN(内容分发网络)加载 jQuery,速度快且稳定。将以下代码添加到 HTML 文件的 <head> 或 <b…

vue实现滚动加载

vue实现滚动加载

滚动加载的实现方法 滚动加载是一种常见的前端交互方式,适用于长列表或数据量大的场景。Vue中可以通过监听滚动事件或使用Intersection Observer API实现。 使用滚动事件监听 在V…

vue实现分页加载

vue实现分页加载

Vue 分页加载的实现方法 基础分页实现(后端分页) 安装依赖(如使用axios): npm install axios 示例代码: <template> <div…

vue的实现方式

vue的实现方式

Vue 的实现方式 Vue 是一个渐进式 JavaScript 框架,其核心实现基于响应式系统和虚拟 DOM。以下是 Vue 的主要实现方式和技术细节: 响应式系统 Vue 使用 Object.de…

vue iview实现方式

vue iview实现方式

Vue + iView 实现方式 安装 iView 在 Vue 项目中安装 iView 库,可以通过 npm 或 yarn 进行安装: npm install view-ui --save 或 y…

vue加载更多实现

vue加载更多实现

滚动监听实现加载更多 通过监听滚动事件判断是否到达底部触发加载。在组件的mounted钩子中添加滚动事件监听器,计算滚动位置与文档高度的关系。 mounted() { window.addEve…