懒加载定义图片的懒加载其实就是懒加载。即不需要一次性加载所有图片,等用户需要某张图片时再加载,避免同时请求大量数据。即当图片滚动到可见区域时,再加载图片。指令除了Vue中常用的v-show、v-bind等指令外,还可以自定义指令。由于自定义命令过于简单,这里只是大致介绍一下可以使用的钩子函数的作用。bind:只调用一次,当指令绑定到一个元素上,就可以用来初始化了。inserted:绑定元素插入父节点时调用。在component文件夹下新建LazyLoad文件夹,文件夹内新建index.js。代码如下:constLazyLoad={//安装方法install(Vue,options){//替换图片的加载图片letdefaultSrc=options.default;Vue.directive('lazy',{bind(el,binding){LazyLoad.init(el,binding.value,defaultSrc);},inserted(el){//兼容处理if('IntersectionObserver'inwindow){LazyLoad.observe(el);}else{LazyLoad.listenerScroll(el);}},})},//初始化init(el,val,def){//data-src存储真实的srcel.setAttribute('data-来源',价值);//设置src为加载图片el.setAttribute('src',def);},//使用IntersectionObserver监控elobserve(el){vario=newIntersectionObserver(entries=>{letrealSrc=el.dataset.src;if(entries[0].isIntersecting){if(realSrc){el.src=真实源;el.removeAttribute('data-src');}}});io.observe(el);},//监听滚动事件listenerScroll(el){lethandler=LazyLoad.throttle(LazyLoad.load,300);LazyLoad.load(el);window.addEventListener('scroll',()=>{handler(el);});},//加载真实图片load(el){letwindowHeight=document.documentElement.clientHeightletelTop=el.getBoundingClientRect().top;让elBtm=el.getBoundingClientRect().bottom;让realSrc=el.dataset.src;if(elTop-windowHeight<0&&elBtm>0){if(realSrc){el.src=realSrc;el.removeAttribute('data-src');}}},//节流throttle(fn,delay){lettimer;让上一个时间;返回函数(...args){让currTime=Date.now();让上下文=这个;如果(!prevTime)公关evTime=当前时间;清除超时(计时器);如果(currTime-prevTime>delay){prevTime=currTime;fn.apply(上下文,参数);清除超时(计时器);返回;}timer=setTimeout(function(){prevTime=Date.now();timer=null;fn.apply(context,args);},delay);}}}导出默认的LazyLoad;添加importLazyLoadfrom'./components/LazyLoad';看。使用(LazyLoad,{default:'https://tva1.sinaimg.cn/large/007S8ZIlgy1gfyof9vr4mj3044032dfl.jpg'});在组件007S8ZIlgy1gfynwi1sejj30ij0nrdx0.jpg"/>中使用
