在使用unapp开发的时候需要用到图片上传,基于业务需求封装了一个图片上传的组件,可以设置最大上传数,删除图片,图片大小自定义。
html部分
<view class="grid-img">
<view
v-for="(item, index) in imgList"
:key="index"
class="img-view"
:style="{ width: wihe[0], height: wihe[1] }"
>
<image class="imgs" :src="item" :style="{ width: wihe[0], height: wihe[1] }"></image>
<view class="img-close" @click="closeItem(index)">
<u-icon name="close" color="#fff" size="10"></u-icon>
</view>
</view>
<view
v-if="imgList.length < maxCount"
:maxCount="maxCount"
:multiple="multiple"
@click="startUpload"
>
<view
class="upload-view"
:style="{ width: wihe[0], height: wihe[1] }"
>
<u-icon name="plus" size="20" bold color="#BFBFBF"></u-icon>
</view>
</view>
</view>
设置props接收
imgList: {
type: Array,
default: () => []
},
maxCount: {
type: Number,
default: 1
},
wihe: {
type: Array,
default: () => ['150rpx', '150rpx']
},
multiple: {
type: Boolean,
default: false
},
maxLength: {
type: Number,
default: 100
}
方法
// 点击上传
startUpload() {
let _this = this;
uni.chooseImage({
count: this.maxCount, // 选择的数量
sizeType: ['original', 'compressed'],
success: (res) => {
const tempFilePaths = res.tempFilePaths;
uni.showLoading({
title: '图片上传中'
});
uni.uploadFile({
url: config.BASE_URL + 'api/upload', //上传的地址
filePath: tempFilePaths[0], //哪张图片
name: 'file',
header: {
//请求头
Authorization: uni.getStorageSync('token'),
},
// 成功的回调
success: (res) => {
uni.hideLoading();
let result = JSON.parse(res.data);
if (result.code == 200) {
_this.uploadSucces(result);
} else {
_this.$u.toast(result.msg);
}
},
fail: (err) => {
uni.hideLoading();
//失败的回调
console.log(err, '!!!!!!!!!!!!!!!!!!');
}
});
}
});
},
// 上传成功后将图片地址放进数组
uploadSucces(result) {
this.imgList.push(result.data);
},
// 点击x图标删除图片
closeItem(index) {
let list = JSON.parse(JSON.stringify(this.imgList));
this.imgList.splice(index, 1);
}
使用 imgList: 绑定的图片列表,数组类型
maxCount:设置最大可添加图片的数量
wihe:设置大小
<uploadPhoto
:imgList="form.image"
:maxCount="3"
wihe="['150rpx', '150rpx']"
>
</uploadPhoto>