一、预期成果
1. 图片上传 + 回显
2.上传成功后自动弹出下一个上传区域
3.组件化拿来即用,组件会将上传结果返回给父组件
<imageUpdata imgList="{
{imageList}}" bind:sendImageUrl="sendImageUrl"></imageUpdata>
sendImageUrl(e) {
this.setData({
imageList: e.detail
})
},
二、代码
1.wxml代码
<view class="content">
<view bindtap="checkImage" wx:for="{
{imgList}}" wx:key="index" data-index="{
{index}}" class="image_item">
<image class="content_img" src="{
{item.url}}" mode=""/>
<image class="content_add" src="../../images/home/add.png" mode=""/>
</view>
</view>
2.wxss代码
/* components/imageUpdata/image_updata.wxss */
.content {
display: flex;
align-items: center;
flex-wrap: wrap;
}
.image_item {
width: 200rpx;
height: 200rpx;
box-sizing: border-box;
margin-bottom: 20rpx;
margin-right: 20rpx;
border: 3rpx dashed #d3d7d4;
border-radius: 10rpx;
display: flex;
align-items: center;
justify-content: center;
}
.content_img {
width: 200rpx;
height: 200rpx;
}
.content_add {
width: 80rpx;
height: 80rpx;
position: absolute;
}
3.js代码
// components/imageUpdata/image_updata.js
Component({
/**
* 组件的属性列表
*/
properties: {
imgList: {
type: Array,
value: [{
index: 0
}, ],
}
},
/**
* 组件的初始数据
*/
data: {
// imgList: [{
// index: 0
// }, ],
userInfo: wx.getStorageInfoSync("userInfo")
},
/**
* 组件的方法列表
*/
methods: {
checkImage(event) {
const that = this;
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album', 'camera'],
camera: 'back',
success(res) {
wx.showLoading({
title: '上传中',
})
console.log(res.tempFiles)
let time = Date.parse(new Date())
wx.cloud.uploadFile({
// 指定上传到的云路径
cloudPath: `FC${that.data.userInfo.name}${time}.png`,
// 指定要上传的文件的小程序临时文件路径
filePath: res.tempFiles[0].tempFilePath,
// 成功回调
success: res => {
wx.cloud.getTempFileURL({
fileList: [res.fileID, ],
success: res => {
console.log(res);
// let a = that.data.imgList.length;
that.data.imgList.forEach((item, indes) => {
if (indes == event.currentTarget.dataset.index) {
let temp = that.data.imgList;
temp[indes].url = res.fileList[0].tempFileURL;
let Yarr = that.data.imgList.filter((item) => {
return item.url
})
if (that.data.imgList.length == Yarr.length) {
temp.push({
index: that.data.imgList.length
});
}
that.setData({
imgList: temp
})
// 将数据发送给父组件
that.sendImageUrl()
wx.hideLoading()
}
})
},
fail: err => {
console.log("报错了", err)
}
})
},
fail: err => {
wx.hideLoading();
wx.showToast({
title: '上传失败',
icon:"none"
})
}
})
}
})
},
sendImageUrl() {
this.triggerEvent("sendImageUrl", this.data.imgList)
},
}
})