当前位置:首页 > 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 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身:…

vue实现定位

vue实现定位

Vue 中实现定位的方法 在 Vue 中实现定位可以通过以下几种方式: 使用 CSS 定位 通过 CSS 的 position 属性实现定位,Vue 中可以直接在组件的 <style>…

vue课程实现

vue课程实现

Vue 课程实现方案 课程内容设计 Vue课程应从基础到高级逐步展开,涵盖Vue核心概念、组件化开发、状态管理、路由、构建工具等。基础部分包括Vue实例、模板语法、计算属性和侦听器。中级部分深入组件通…

实现vue table

实现vue table

Vue 表格实现方法 基础表格实现 使用 Vue 的 v-for 指令可以快速渲染表格数据。在模板中定义表格结构,通过数据绑定动态生成行和列。 <template> <tabl…

vue 实现搜索

vue 实现搜索

实现 Vue 搜索功能 在 Vue 中实现搜索功能通常涉及以下几个关键步骤: 数据绑定与输入监听 使用 v-model 双向绑定搜索输入框的值,监听用户输入: <template>…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,支…