1 Vue.component('my-wx-upload', { 2 template: ` 34 15 `,16 props: {17 imgList: {type: Array},18 chooseImage: {type: Number, default: 9},19 },20 data() {21 return {22 readyUploadImages: []23 }24 },25 mounted() {26 this.readyUploadImages = this.imgList27 },28 methods: {29 remove(index) {30 this.readyUploadImages.splice(index, 1)31 },32 add() {33 wx.chooseImage({34 count: this.oddchooseImageCount, // 最多可以选择的图片张数,默认935 sizeType: ['original'], // original 原图,compressed 压缩图,默认二者都有36 sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有37 success: res => {38 this.readyUploadImages = this.readyUploadImages.concat(res.localIds);39 // myUpImageBlock40 },41 fail: function () {42 // fail43 },44 complete: function () {45 // complete46 }47 })48 },49 preview(img) {50 wx.previewImage({51 current: img, // 当前显示图片的http链接52 urls: this.readyUploadImages // 需要预览的图片http链接列表53 });54 }55 },56 computed: {57 oddchooseImageCount() {58 return this.chooseImage - this.readyUploadImages.length;59 },60 uploadIsFull() {61 return this.readyUploadImages.length !== this.chooseImage62 }63 },64 watch: {65 readyUploadImages(val) {66 this.$emit('update:imgList', val)67 }68 }69 });5 6 107 8911 13 14
调用方法
<my-wx-upload :img-list.sync="传入一个数组"></my-wx-upload>
上传方法
WxUploadImage(imgList) { return new Promise((resolve, reject) => { if (imgList && imgList instanceof Array && imgList.length > 0) { let promiseList = []; for (let i = 0; i < imgList.length; i++) { promiseList[i] = new Promise((resolve, reject) => { wx.uploadImage({ localId: imgList[i], success: res => { resolve(res.serverId); }, fail: error => { reject(error); } }) }); } Promise.all(promiseList) .then(result => { resolve(result); }) .then(error => { reject(error); }) } else { reject('传参有误,请传数组格式'); } }) }
调用方法
this.WxUploadImage(this.imageList).then(res => { });