UNPKG

@tarojs/components

Version:
60 lines (56 loc) • 3.12 kB
import { r as registerInstance, c as createEvent, h, H as Host } from './index-0004ce39.js'; import { c as classnames } from './index-b9522531.js'; const indexCss = "img[src=\"\"]{opacity:0}:where(taro-image-core){width:320px;height:240px;font-size:0;display:inline-block;position:relative;overflow:hidden}:where(taro-image-core.taro-img__disable-default-size){width:auto;height:auto}.taro-img.taro-img__widthfix{height:100%}.taro-img__mode-scaletofill{width:100%;height:100%}.taro-img__mode-aspectfit{max-width:100%;max-height:100%;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.taro-img__mode-aspectfill{object-fit:cover;width:100%;height:100%}.taro-img__mode-widthfix{width:100%}.taro-img__mode-heightfix{height:100%}.taro-img__mode-top{position:absolute;left:50%;transform:translate(-50%)}.taro-img__mode-bottom{position:absolute;bottom:0;left:50%;transform:translate(-50%)}.taro-img__mode-center{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.taro-img__mode-left{position:absolute;top:50%;transform:translateY(-50%)}.taro-img__mode-right{position:absolute;top:50%;right:0;transform:translateY(-50%)}.taro-img__mode-topright{position:absolute;right:0}.taro-img__mode-bottomleft{position:absolute;bottom:0}.taro-img__mode-bottomright{position:absolute;bottom:0;right:0}"; const Image = class { constructor(hostRef) { registerInstance(this, hostRef); this.onLoad = createEvent(this, "load", 7); this.onError = createEvent(this, "error", 7); this.src = undefined; this.mode = 'scaleToFill'; this.lazyLoad = false; this.nativeProps = {}; this.disableDefaultSize = false; this.didLoad = false; } componentDidLoad() { if (!this.lazyLoad || !this.imgRef) return; const lazyImg = new IntersectionObserver(entries => { // 异步 api 关系 if (entries[entries.length - 1].isIntersecting) { this.imgRef && lazyImg.unobserve(this.imgRef); this.didLoad = true; } }, { rootMargin: '300px 0px' }); lazyImg.observe(this.imgRef); } imageOnLoad() { // 防止组件已卸载或 img 已被移除时 ref 为 null(如列表滚动、src 清空、lazyLoad 时序等) if (!this.imgRef) return; const { width, height } = this.imgRef; this.onLoad.emit({ width, height }); } imageOnError(e) { this.onError.emit(e); } render() { const { src, lazyLoad = false, imageOnLoad, imageOnError, nativeProps, didLoad } = this; // mode="" 按默认值处理 const mode = this.mode || 'scaleToFill'; const cls = classnames({ 'taro-img__widthfix': mode === 'widthFix', 'taro-img__disable-default-size': this.disableDefaultSize, }); const imgCls = `taro-img__mode-${mode.toLowerCase().replace(/\s/g, '')}`; return (h(Host, { class: cls }, src ? (h("img", Object.assign({ ref: (img) => (this.imgRef = img), class: imgCls, src: lazyLoad && !didLoad ? undefined : src, onLoad: imageOnLoad.bind(this), onError: imageOnError.bind(this) }, nativeProps))) : '')); } }; Image.style = indexCss; export { Image as I };