MST
星途 面试题库

面试题:深入Vue生命周期钩子优化懒加载性能

假设一个包含大量图片列表的Vue页面,使用生命周期钩子实现懒加载。请阐述如何在不同的生命周期钩子中配合使用防抖或节流技术,以优化懒加载过程中的性能,避免频繁触发加载操作,并给出相应的代码示例。
24.2万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

1. 懒加载原理及生命周期钩子选择

在Vue中,mounted 生命周期钩子适合用于初始化页面时的操作,而懒加载通常在页面滚动过程中触发。因此,我们可以在 mounted 中绑定页面滚动事件,然后在滚动事件处理函数中实现懒加载逻辑。

2. 防抖和节流技术

  • 防抖(Debounce):在事件触发后,等待一定时间(例如300ms),如果这段时间内事件再次触发,则重新计时。只有在最后一次触发事件后的等待时间结束后,才执行实际的操作。这可以避免在短时间内频繁触发事件。
  • 节流(Throttle):规定在一定时间间隔内(例如200ms),无论事件触发多少次,都只执行一次实际操作。

3. 代码示例

<template>
  <div id="app">
    <img v-for="(image, index) in images" :key="index" :data-src="image.src" @load="handleImageLoad(index)" lazy-load>
  </div>
</template>

<script>
// 自定义指令实现懒加载
const lazyLoadDirective = {
  inserted(el, binding) {
    const observer = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          el.src = binding.value;
          observer.unobserve(el);
        }
      });
    });
    observer.observe(el);
  }
};

export default {
  name: 'App',
  directives: {
    lazyLoad: lazyLoadDirective
  },
  data() {
    return {
      images: [
        { src: 'image1.jpg' },
        { src: 'image2.jpg' },
        // 更多图片...
      ],
      loadedImages: []
    };
  },
  mounted() {
    // 使用节流优化滚动事件
    const throttleScroll = this.throttle(this.handleScroll, 200);
    window.addEventListener('scroll', throttleScroll);
  },
  methods: {
    handleImageLoad(index) {
      this.loadedImages.push(index);
    },
    handleScroll() {
      // 懒加载逻辑
      // 这里简单示意,实际需要判断图片是否在视口内
      console.log('Scroll event, check for lazy load');
    },
    // 节流函数实现
    throttle(func, wait) {
      let timeout;
      return function() {
        const context = this;
        const args = arguments;
        if (!timeout) {
          func.apply(context, args);
          timeout = setTimeout(() => {
            timeout = null;
          }, wait);
        }
      };
    }
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

在上述代码中:

  • 自定义了一个 lazyLoad 指令来实现基本的图片懒加载逻辑。
  • mounted 生命周期钩子中使用 addEventListener 绑定了 scroll 事件,并使用节流函数 throttle 对滚动事件处理函数 handleScroll 进行优化,避免频繁触发,提高性能。