跟随Element学习Vue小技巧(54)——Image

1,062 阅读4分钟

如果你有梦想的话

就要去捍卫它

前言

人生苦短,必须性感! 嘻嘻嘻 (#^.^#)

1 Image

懒加载 lazy

代码片段

<img
  ...
  :src="src"
  :style="imageStyle"
  :class="{ 'el-image__inner--center': alignCenter, 'el-image__preview': preview }">
  
mounted() {
  if (this.lazy) {
    this.addLazyLoadListener();
  } else {
    this.loadImage();
  }
}
addLazyLoadListener() {
  ...
  if (_scrollContainer) {
    this._scrollContainer = _scrollContainer;
    this._lazyLoadHandler = throttle(200this.handleLazyLoad);
    on(_scrollContainer, 'scroll'this._lazyLoadHandler);
    this.handleLazyLoad();
  }
}

handleLazyLoad() {
  if (isInContainer(this.$el, this._scrollContainer)) {
    this.show = true;
    this.removeLazyLoadListener();
  }
}

watch: {
  show(val) {
    val && this.loadImage();
  }
}

loadImage() {
  ...
  const img = new Image();
  img.onload = e => this.handleLoad(e, img);
  img.onerror = this.handleError.bind(this);
  ...
  img.src = this.src;
}

技巧解析

懒加载,意味着平时摸鱼,领导视察时认真一下下啦
如果图片不在容器中,src为空
如果图片在容器中,给src赋值
怎么知道是否在容器中呢?
下面的小工具告诉你 ^_^

安全策略 Referrer

代码片段

<img 
  href="http://example.com/img/1.png" 
  referrerpolicy="origin">

技巧解析

想知道我从哪里来的吗?
no-referrer,就不告诉你
origin,稍微给你一点提示吧
same-origin,既然是老乡,就告诉你吧
更多好玩的,传送门发给你

Referrer-Policy 传送门

小工具

isInContainer

代码片段

elRect.top<containerRect.bottom

elRect.bottom > containerRect.top

/*
* @ {desc} 图片元素在容器中
* @ {params} el-图片 container-容器
* @ {example}
    1.elRect.top < containerRect.bottom
    图片进入容器,图片顶部触及容器底部
    
    2.elRect.bottom > containerRect.top
    图片离开容器,图片底部触及容器顶部
    
*/
export const isInContainer = (el, container) => {
  if (isServer || !el || !container) return false;

  const elRect = el.getBoundingClientRect();
  let containerRect;

  if ([windowdocumentdocument.documentElementnullundefined].includes(container)) {
    containerRect = {
      top0,
      rightwindow.innerWidth,
      bottomwindow.innerHeight,
      left0
    };
  } else {
    containerRect = container.getBoundingClientRect();
  }

  return elRect.top < containerRect.bottom &&
    elRect.bottom > containerRect.top &&
    elRect.right > containerRect.left &&
    elRect.left < containerRect.right;
};



因为Ta 我才是现在的我

参考链接

往期回顾