当前位置:首页 > VUE

vue实现延迟加载

2026-02-18 07:12:03VUE

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-ifsetTimeout 延迟渲染:

<div v-if="showComponent">
  <heavy-component />
</div>
data() {
  return { showComponent: false }
},
mounted() {
  setTimeout(() => {
    this.showComponent = true
  }, 2000)
}

注意事项

  • 图片懒加载需设置默认占位图避免布局抖动
  • 路由懒加载会产生独立 chunk 文件
  • 移动端注意 IntersectionObserver 的兼容性
  • 服务端渲染(SSR)场景需特殊处理懒加载逻辑

vue实现延迟加载

标签: 加载vue
分享给朋友:

相关文章

vue设计与实现 书

vue设计与实现 书

vue设计与实现 书 《Vue.js设计与实现》是一本深入探讨Vue.js框架内部原理和设计思想的书籍,适合希望深入理解Vue.js的开发者。以下是关于这本书的详细信息: 书籍内容 《Vue…

vue 实现豆瓣

vue 实现豆瓣

以下是基于 Vue 实现豆瓣电影类功能的实现方案,涵盖核心模块和技术要点: 数据获取与 API 调用 使用豆瓣开放 API(需注意调用频率限制)或第三方代理接口 推荐 axios 进行异步请求,配合…

vue实现批量

vue实现批量

Vue 实现批量操作的方法 在 Vue 中实现批量操作通常涉及选择多个项目并执行统一处理,例如批量删除、批量更新等。以下是几种常见实现方式: 表格多选批量操作 使用 el-table 配合复选框实…

vue实现switch

vue实现switch

Vue 实现 Switch 开关组件 在 Vue 中实现 Switch 开关组件可以通过自定义组件或使用现有 UI 库完成。以下是几种常见实现方式: 自定义 Switch 组件 创建一个基础…

vue实现剪辑

vue实现剪辑

Vue 实现视频剪辑功能 在Vue中实现视频剪辑功能通常需要结合HTML5的<video>元素和第三方库(如FFmpeg.js或Video.js)。以下是几种常见的实现方法: 使用FF…

vue实现flvvideo

vue实现flvvideo

vue-flv-player 实现 FLV 视频播放 安装依赖包 npm install flv.js vue-flv-player 基础组件引入 <template> <v…