当前位置:首页 > 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 延迟渲染:

vue实现延迟加载

<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 CLI 或 Vite 初始化项目,安装必要依赖(如 Vue 3、Element UI 或 Vuetify 用于 UI 组件)。 npm c…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…

jquery实现vue

jquery实现vue

jQuery 和 Vue.js 是两种不同理念的前端工具,jQuery 以 DOM 操作和事件驱动为核心,而 Vue.js 是数据驱动的现代化框架。如果想用 jQuery 实现类似 Vue 的功能(如…

vue实现上传

vue实现上传

Vue 文件上传实现方法 使用 Vue 实现文件上传可以通过原生 HTML5 的 <input type="file"> 元素结合 Vue 的事件处理和数据绑定来实现。 基础实现步骤…

vue实现mouseout

vue实现mouseout

Vue 实现 mouseout 事件的方法 在 Vue 中实现 mouseout 事件可以通过多种方式完成,以下是几种常见的方法: 使用 v-on 指令 Vue 提供了 v-on 指令(或简写为 @…

vue实现selectable

vue实现selectable

Vue 实现可选择的 Select 组件 在 Vue 中实现一个可选择的 Select 组件,可以通过以下几种方式: 使用原生 HTML select 元素 <template> &…