1.项目需要很多个图片上传然后为了节省代码,就把他封起来了
首先看一下效果-上传后的样子,和没有上传的样子
**1. 配置自定义组件 首先在app.js同级新建一个components的文件夹,放我们的公共组件 **
我们在components文件夹里面新建一个 pictureUpload 的文件,自动生成页面
然后wxml
<van-uploader bind:after-read="afterRead">
<view class="pictureUpload">
<image wx:if="{{list.shen}}" class="exhibition" src="{{list.shen}}"></image>
<image wx:else src="https://vehicle-library.oss-cn-beijing.aliyuncs.com/cvbd-icon/plus_20210524103032.png"></image>
</view>
</van-uploader>
<view class="text" hover-class="none" hover-stop-propagation="false">{{title}}</view>
wxss
.pictureUpload {
width: 690rpx;
height: 388rpx;
background: #AFCDF3;
margin: 0 auto;
margin-top: 20rpx;
display: flex;
justify-content: center;
align-items: center;
border-radius: 10rpx;
}
.pictureUpload image {
width: 60rpx;
height: 60rpx;
}
.pictureUpload .exhibition {
width: 100%;
height: 100%;
border-radius: 10rpx;
}
.text {
width: 100%;
height: 40rpx;
text-align: center;
font-size: 30rpx;
font-family: PingFangSC-Medium, PingFang SC;
font-weight: 500;
color: #333333;
margin-top: 20rpx;
}
wxjs
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
properties: {
index: {
type: String,
value: ''
},
title: {
type: String,
value: '',
},
},
data: {
list: { shen: "" },
uploadAddress: [
"www.daidu.com",
"www.daidu.com",
"www.daidu.com",
"www.daidu.com"
],
},
methods: {
afterRead: function(event) {
let index = this.properties.index // 拿到传递过来的下标
console.log(this.properties.uploadAddress[index])
var that = this
const { file } = event.detail;
wx.compressImage({
src: file.url, // 图片路径
quality: 0, // 压缩质量
success: function(res) {
let token = wx.getStorageSync('token')
wx.uploadFile({
url: that.properties.uploadAddress[index], // 仅为示例,非真实的接口地址 // 仅为示例,非真实的接口地址
method: 'POST',
header: { "Authorization": "Bearer " + token },
filePath: res.tempFilePath,
name: 'image',
formData: { user: 'test' },
success(res) {
if (JSON.parse(res.data).code != 200) return console.log("500")
that.setData({
["list.shen"]: JSON.parse(res.data).data.imgUrl
})
that.triggerEvent("Image", { imgUrl: JSON.parse(res.data).data.imgUrl, title: that.properties.title })
},
});
}
})
}
},
})
**组件封装完成 来到 index.js引入 **
{
"usingComponents": {
"popup": "/components/pictureUpload/pictureUpload"
},
"navigationBarTitleText": "index"
}
index.wxml 直接调用
<popup index='2' title='身份证(正面)' bind:Image="Image"></popup>
index.wxss
Image(e) {
console.log('图片地址是:' + e.detail.imgUrl)
console.log('点击的图片是:' + e.detail.title)
this.setData({
["list.shen"]: e.detail.imgUrl
})
},
最终效果就有了,