面试题答案
一键面试1. 使用 vue-lazyload
插件实现图片懒加载
- 安装插件:
在项目根目录下运行
npm install vue-lazyload --save
或yarn add vue-lazyload
安装插件。 - 全局配置与使用:
在
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 // 加载失败后重试次数 });
- 在模板中使用:
在需要懒加载的图片标签上使用
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 手动实现(不依赖插件)
- 创建自定义指令:
在
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;
- 全局注册指令:
在
main.js
中注册指令。import Vue from 'vue'; import lazyload from './directives/lazyload'; Vue.directive('lazyload', lazyload);
- 在模板中使用:
<template> <div> <img v - lazyload="imgUrl" alt="example"> </div> </template> <script> export default { data() { return { imgUrl: 'https://example.com/image.jpg' }; } }; </script>