基於 vant-ui 封裝一個微信公眾號上傳插件
阿新 • • 發佈:2019-03-19
公眾 font upload style vue asset splice computed img
1 Vue.component(‘my-wx-upload‘, { 2 template: ` 3 <mu-grid-list :cols="3" :cellHeight="90"> 4 <mu-grid-tile titleBarClass v-for="img, index in readyUploadImages" :key="index"> 5 <img :src="img" @click="preview(img)"/> 6 <div slot="action"> 7<i @click="remove(index)" class="iconfont icondelete" style="color: white;font-size: 2em;"></i> 8 </div> 9 </mu-grid-tile> 10 <mu-grid-tile v-show="uploadIsFull" hideTitleBarClass> 11 <img @click="add" imgAdd 12 src="/assets/public/wx/cms/img/add.jpg"/> 13</mu-grid-tile> 14 </mu-grid-list> 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.imgList 27 }, 28 methods: { 29 remove(index) { 30 this.readyUploadImages.splice(index, 1) 31 }, 32 add() { 33 wx.chooseImage({ 34 count: this.oddchooseImageCount, // 最多可以選擇的圖片張數,默認9 35 sizeType: [‘original‘], // original 原圖,compressed 壓縮圖,默認二者都有 36 sourceType: [‘album‘, ‘camera‘], // album 從相冊選圖,camera 使用相機,默認二者都有 37 success: res => { 38 this.readyUploadImages = this.readyUploadImages.concat(res.localIds); 39 // myUpImageBlock 40 }, 41 fail: function () { 42 // fail 43 }, 44 complete: function () { 45 // complete 46 } 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.chooseImage 62 } 63 }, 64 watch: { 65 readyUploadImages(val) { 66 this.$emit(‘update:imgList‘, val) 67 } 68 } 69 });
調用方法
<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 => { });
基於 vant-ui 封裝一個微信公眾號上傳插件