MST

星途 面试题库

面试题:Vue 懒加载在大型项目中如何优化图片资源加载性能

在一个大型 Vue 项目中,有大量图片需要展示。请阐述使用 Vue 懒加载优化图片资源加载性能的具体实现方式,包括涉及到的 Vue 指令、组件或插件,以及如何配置和使用它们。
38.0万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

1. 使用 vue-lazyload 插件实现图片懒加载

  1. 安装插件: 在项目根目录下运行 npm install vue-lazyload --saveyarn add vue-lazyload 安装插件。
  2. 全局配置与使用: 在 main.js 中引入并配置 vue-lazyload
    import Vue from 'vue';
    import VueLazyload from 'vue-lazyload';
    
    Vue.use(VueLazyload, {
      // 配置项
      preLoad: 1.3, // 预加载高度比例,1.3 表示在距离视口高度 1.3 倍时开始加载图片
      error: require('./assets/error.png'), // 图片加载失败时显示的图片路径
      loading: require('./assets/loading.gif'), // 图片加载中显示的图片路径
      attempt: 3 // 加载失败后重试次数
    });
    
  3. 在模板中使用: 在需要懒加载的图片标签上使用 v - lazy 指令替代 src 属性。
    <template>
      <div>
        <img v - lazy="imgUrl" alt="example">
      </div>
    </template>
    <script>
    export default {
      data() {
        return {
          imgUrl: 'https://example.com/image.jpg'
        };
      }
    };
    </script>
    

2. 基于 Intersection Observer API 手动实现(不依赖插件)

  1. 创建自定义指令: 在 directives 文件夹下创建 lazyload.js 文件。
    const lazyload = {
      inserted(el, binding) {
        const observer = new IntersectionObserver((entries) => {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              el.src = binding.value;
              observer.unobserve(el);
            }
          });
        });
        observer.observe(el);
      }
    };
    
    export default lazyload;
    
  2. 全局注册指令: 在 main.js 中注册指令。
    import Vue from 'vue';
    import lazyload from './directives/lazyload';
    
    Vue.directive('lazyload', lazyload);
    
  3. 在模板中使用
    <template>
      <div>
        <img v - lazyload="imgUrl" alt="example">
      </div>
    </template>
    <script>
    export default {
      data() {
        return {
          imgUrl: 'https://example.com/image.jpg'
        };
      }
    };
    </script>