import system from 'bsl-build/system'; import { isHttp } from 'bsl-core/utils/lang'; import C from 'bsl-mp/app/Component'; import Event from 'bsl-mp/typings/event'; import { getGlobalData } from 'bsl-mp/utils/globalData'; import * as Export from './export'; const computedBehavior = require('miniprogram-computed').behavior; const state = { realSrc: '', ready: false, width: 0, height: 0 }; class Instance extends C { constructor() { super(state, { extClass: String, src: String, srcs: Array, mode: { type: String, value: 'aspectFill' }, lazyLoad: Boolean, preview: Boolean, hidden: Boolean, defaultImage: String, width: String, height: String, host: String }); } public behaviors = [computedBehavior]; public externalClasses = ['wrap-cls']; public watch = { 'src'() { const self = this as any as Instance; self.setData({ realSrc: self.setSrc(self.properties.src) }); } }; public ready() { this.setData({ realSrc: this.setSrc(this.properties.src) }); } public setSrc(src?: string) { if (src) { if (!isHttp(src)) { let host = this.properties.host || getGlobalData().__image__.defaultHost; if (host === 'publicPath') { host = system.env === 'development' ? '' : system.publicPath; } return host + src; } else { return src; } } else { const imageConfig = getGlobalData().__image__; return imageConfig.defaultHost + imageConfig.defaultImage; } } public bindPreviewImage(e: Event.Tap) { const src = this.data.realSrc; if (this.properties.preview) { const srcs = this.properties.srcs; const urls = srcs.length ? srcs.map((item) => this.setSrc(item)) : [src]; const current = urls.find((item) => item === src); wx.previewImage({ current, urls }); } this.triggerEvent!('onClick', e.detail); } public bindError(e: Event.Error) { const config = getGlobalData().__image__; const defaultImage = this.properties.defaultImage || config.defaultImage; this.groupSetData(() => { this.setData({ ready: true }, () => { this.triggerEvent('complete', e.detail); this.triggerEvent('error', e.detail); }); if (defaultImage) { this.setData({ realSrc: defaultImage }); } }); } public bindLoad(e: Event.ImageLoad) { this.setData({ ready: true, width: this.properties.width === 'auto' ? e.detail.width : this.properties.width, height: this.properties.height === 'auto' ? e.detail.height : this.properties.height, }, () => { this.triggerEvent('complete', e.detail); this.triggerEvent('load', e.detail); }); } } Component(new Instance().init());