当前位置:首页 > 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 的监听能力主要基于其响应式系统,该系统通过数据劫持和依赖收集实现。当数据变化时,系统能自动触发视图更新或执行回调函数。 核心机制:Object.definePrope…

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

vue实现groupbox

vue实现groupbox

Vue 实现 GroupBox 组件 在 Vue 中实现类似 GroupBox 的效果可以通过自定义组件完成。GroupBox 通常是一个带有标题的边框容器,用于将相关控件分组显示。 基本实现方法…

vue实现pc

vue实现pc

Vue 实现 PC 端应用开发 Vue.js 是一个流行的前端框架,适用于构建 PC 端 Web 应用。以下是关键步骤和最佳实践: 项目初始化 使用 Vue CLI 或 Vite 创建项目:…

自实现vue

自实现vue

实现 Vue 的核心功能 要实现一个简化版的 Vue,需要理解其核心功能:数据响应式、模板编译、虚拟 DOM 和组件系统。以下是关键步骤的分解: 数据响应式 Vue 使用 Object.define…

vue实现type切换

vue实现type切换

Vue 实现 Type 切换的实现方法 在 Vue 中实现 Type 切换功能可以通过动态组件、条件渲染或路由切换等方式实现。以下是几种常见方法: 使用 v-if 或 v-show 条件渲染 通过绑…