面试题答案
一键面试使用第三方插件 vue - lazyload
- 安装:通过npm或yarn安装
vue - lazyload
。- 使用npm:
npm install vue - lazyload --save
- 使用yarn:
yarn add vue - lazyload
- 使用npm:
- 全局配置:在Vue项目的入口文件(如
main.js
)中引入并配置。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 // 图片加载失败后重试次数 });
- 图片元素配置:在模板中使用
v - lazy
指令。<template> <div> <img v - lazy="imageUrl" alt="example"> </div> </template> <script> export default { data() { return { imageUrl: 'https://example.com/image.jpg' }; } }; </script>
使用IntersectionObserver API手动实现(不依赖第三方插件)
- 指令定义:在Vue项目中定义一个自定义指令。可以在
directives
目录下创建一个文件,例如lazyload.js
。const lazyload = { 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 lazyload;
- 全局注册指令:在
main.js
中注册该指令。import Vue from 'vue'; import lazyload from './directives/lazyload'; Vue.directive('lazyload', lazyload);
- 图片元素配置:在模板中使用自定义的
v - lazyload
指令。<template> <div> <img v - lazyload="imageUrl" alt="example"> </div> </template> <script> export default { data() { return { imageUrl: 'https://example.com/image.jpg' }; } }; </script>
使用Vue内置的 v - show
配合计算属性模拟懒加载(简单场景)
- 数据和计算属性:在组件的
data
中定义图片是否可见的状态,以及一个计算属性来判断图片是否在视口内(这里只是简单模拟,实际需要更复杂的视口判断逻辑)。<template> <div> <img v - show="isImageVisible" :src="imageUrl" alt="example"> </div> </template> <script> export default { data() { return { imageUrl: 'https://example.com/image.jpg', isImageVisible: false }; }, computed: { shouldLoadImage() { // 这里简单模拟判断,实际需要更准确的视口判断逻辑 const windowHeight = window.innerHeight; const scrollTop = window.pageYOffset; // 假设图片距离顶部小于窗口高度就加载 return scrollTop + windowHeight > 0; } }, mounted() { window.addEventListener('scroll', this.handleScroll); }, beforeDestroy() { window.removeEventListener('scroll', this.handleScroll); }, methods: { handleScroll() { if (this.shouldLoadImage) { this.isImageVisible = true; } } } }; </script>
在上述方式中,vue - lazyload
插件使用较为方便,功能全面;使用 IntersectionObserver API
手动实现更具灵活性和定制性;而使用 v - show
配合计算属性模拟懒加载适合简单场景,可作为一种轻量级的解决方案。