当前位置:首页 > VUE

vue 实现懒加载

2026-02-18 13:17:38VUE

Vue 实现懒加载的方法

使用 v-lazy 指令(需安装插件)

安装 vue-lazyload 插件:

npm install vue-lazyload --save

main.js 中配置:

import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'error.png',
  loading: 'loading.gif',
  attempt: 1
})

在模板中使用:

vue 实现懒加载

<img v-lazy="imageUrl" alt="Lazy Image">

路由懒加载(动态导入)

通过动态 import() 语法实现路由组件懒加载:

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

组件懒加载

使用 defineAsyncComponent 异步加载组件:

vue 实现懒加载

import { defineAsyncComponent } from 'vue'

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

export default {
  components: {
    AsyncComponent
  }
}

图片懒加载(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 Image">

懒加载占位策略

为懒加载元素添加加载状态:

<div v-if="isLoading">Loading...</div>
<img v-else v-lazy="imageUrl">

<script>
export default {
  data() {
    return {
      isLoading: true
    }
  },
  mounted() {
    this.loadImage()
  },
  methods: {
    loadImage() {
      const img = new Image()
      img.onload = () => {
        this.isLoading = false
      }
      img.src = this.imageUrl
    }
  }
}
</script>

性能优化建议

  • 设置合理的预加载阈值(如 preLoad: 1.3
  • 提供高质量的占位图或加载动画
  • 对移动端可降低图片质量要求
  • 结合 WebP 等现代图片格式
  • 使用 CDN 加速资源加载

以上方法可根据具体场景组合使用,路由懒加载适用于SPA应用,图片懒加载适合媒体资源密集页面。

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

相关文章

vue实现遮罩

vue实现遮罩

Vue 实现遮罩层的方法 在 Vue 中实现遮罩层可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-show 或 v-if 控制显示 通过 Vue 的指令动态控制遮罩层的显示与隐藏。…

vue实现上传

vue实现上传

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

vue多选实现

vue多选实现

Vue 多选实现方法 基础实现(v-model + multiple) 在 Vue 中实现多选可以通过 <select> 元素的 multiple 属性结合 v-model 完成。v-mo…

vue 实现fadeout

vue 实现fadeout

Vue 实现淡出效果 在 Vue 中实现淡出(fade-out)效果可以通过 CSS 过渡或动画结合 Vue 的动态渲染功能完成。以下是几种常见方法: 使用 Vue 过渡(Transition)组件…

vue 实现登录

vue 实现登录

Vue 实现登录功能 创建登录表单组件 在 Vue 项目中创建一个登录表单组件(如 Login.vue),包含用户名和密码输入框以及提交按钮。使用 v-model 实现双向数据绑定。 <tem…

vue jwt实现

vue jwt实现

Vue JWT 实现方法 安装依赖 确保项目中安装了 jsonwebtoken(后端)和 axios(前端)。若使用 Vue 3,可搭配 vue-router 和 pinia(或 vuex)管理状态。…