一、插件(文件存放位置:/components/loader/)
1、img-loader.js
Component({
properties: {},
data: {
imgs: [],
list: [],
success: function () {}
},
lifetimes: {
attached() {}
},
methods: {
//加载
load(opts) {
const that = this
const imgs = opts.imgs || []
const success = opts.success || function () {}
that.setData({
imgs: imgs,
success: success
}, () => {
that.callBack()
})
},
//初始回调
callBack() {
const that = this
const list = that.data.list
list.forEach(item => {
if (item.loaded) {
that.data.success(item)
}
})
},
//成功回调
imgOnLoad(e) {
const that = this
const src = e.currentTarget.dataset.src
const width = e.detail.width
const height = e.detail.height
let list = that.data.list
let has = false
list = list.map(item => {
if (src == item.src) {
has = true
item.loaded = true
}
return item
})
if (!has) {
list.push({
src: src,
width: width,
height: height,
loaded: true
})
}
that.setData({
list: list
}, () => {
that.data.success({
src: src,
width: width,
height: height,
loaded: true
})
})
},
//错误回调
imgOnLoadError(e) {
const that = this
const src = e.currentTarget.dataset.src
that.data.success({
src: src,
loaded: false
})
}
},
attached() {}
})
2、img-loader.json
{
"component": true,
"usingComponents": {}
}
3、img-loader.wxml
<image wx:for="{{imgs}}" wx:key="*this" src="{{item}}" data-src="{{item}}" bindload="imgOnLoad"
binderror="imgOnLoadError" class="img-loader"></image>
4、img-loader.wxss
.img-loader {
display: none;
width: 0;
height: 0;
opacity: 0;
}
二、插件引用方法
1、wxml
<img-loader id="imgLoader"></img-loader>
2、json
{
"usingComponents": {
"img-loader": "/components/loader/img-loader"
}
}
3、js
const app = getApp()
Page({
data: {
photoList:[],
imgList: []
},
onLoad() {},
onReady() {},
onShow() {
const that = this
const actions = [
that.getPhotoList()
]
Promise.all(
actions.map((p) => {
return p.catch(error => error)
})
).then(res => {
let photoList= that.data.photoList
let imgList = that.data.imgList
let has = false
let loaded = false
if (0 == res[0].errcode) {
photoList = res[0].data
photoList = photoList.map(item => {
has = false
loaded = false
imgList.forEach(img => {
if (img.url == item.photo_url) {
has = true
loaded = img.loaded
}
})
if (!has) {
imgList.push({
url: item.photo_url,
loaded: false
})
}
item.loaded = loaded
return item
})
}
that.imgLoader = that.selectComponent('#imgLoader')
that.setData({
photoList: photoList,
imgList: imgList
}, () => {
that.loadImages()
})
}).catch(error => {})
},
//获取照片列表
getPhotoList() {
return app.invokeApi('api_url')
},
//加载图片
loadImages() {
const that = this
let photoList = that.data.photoList
let imgList = that.data.imgList
let imgs = imgList.map(item => {
return item.url
})
that.imgLoader.load({
imgs: imgs,
success: res => {
const src = res.src
if (res.loaded) {
photoList.forEach((item, index) => {
if (src == item.photo_url) {
that.setData({
['photoList[' + index + '].loaded']: true
})
}
})
imgList.forEach((item, index) => {
if (src == item.url) {
that.setData({
['imgList[' + index + '].loaded']: true
})
}
})
}
}
})
}
})