封装vue可视区域图片懒加载
emer 发布于 2018-11-29 15:46 2455 次阅读
export default (Vue) => { var imageCatcheList = []; //初始化数据 var init = { default: 'http://test.group.batmobi.net/dist/image/transprent.png', } //是否已下载 const hasLoad = (src) => { if (imageCatcheList.indexOf(src) > -1) { return true; } else { return false; } } //图片下载处理 const imageLoad = (el, src) => { var image = new Image(); image.onload = function () { el.src = src; imageCatcheList.push(src); } image.src = src; } //是否可以展示 const isCanShow = (el, src) => { //节点离浏览器顶部的距离 var offsetTop = el.offsetTop; //页面可视区域的高度 var windowHeight = window.innerHeight; var scroll = windowHeight + window.scrollY; var offsetHeigth = el.offsetHeight; if (scroll > offsetTop && (window.scrollY - offsetTop) < offsetHeigth) { //查询图片是否已加载过,是则直接加载,否则先load if (hasLoad(src)) { el.src = src; } else { imageLoad(el, src); } } } const addListener = (el, bind) => { var imageSrc = bind.value; //赋值默认值 el.src = init.default; isCanShow(el, imageSrc); window.addEventListener('scroll', function (event) { isCanShow(el, imageSrc, event); }); } Vue.directive('lazy', { inserted: addListener, updated : addListener, }) } 使用方法 在main.js中注册指令 Vue.use(imgLazyload); 1 2 在*.vue组件中加载指令 <img v-lazy="img-url">