微信小程序學習筆記五(持續更新)---小程序上傳文件
阿新 • • 發佈:2018-10-24
gin false round count splice dex 一個 key 屬性
項目中需要用戶上傳圖片,需要實現,上傳按鈕默認為一個,在上傳一張圖片之後,自動增加一個上傳按鈕,上傳三張圖片後按鈕消失。
實現思路:
1、圖片路徑存儲在一個數組中,增加和刪除圖片是對數組進行操作;
2、僅一個按鈕,添加計數器,num=1;當num==3時,設置按鈕隱藏。
直接上代碼:
.wxml文件:
<view class=‘uploader‘ wx:for="{{files}}" wx:key="{{index}}"> <image src=‘../../img/cha.png‘ class=‘cha‘ catchtap=‘delete‘ data-index="{{index}}"></image> <image src=‘{{item}}‘ class=‘upload-img‘ ></image> </view> <view class=‘uploader‘ wx:if="{{upload}}" bindtap="previewImage"> <view class=‘uploader-content‘> <view class=‘add-icon‘>+</view> <view class=‘title‘>添加圖片</view> </view> </view>
.wxss代碼:
.uploader{ position: relative; width: 175rpx; height: 175rpx; background: #F0F0F2; margin-top:50rpx; border-radius:10rpx; float: left; margin-right:20rpx; } .add-icon{ position: absolute; font-size:105rpx; top:-23rpx; left:50rpx; color: #A3A3A3; } .title{ position:absolute; bottom:30rpx; left:32rpx; color:#A3A3A3; font-size:31rpx; } .upload-img{ width: 100%; height: 100%; border-radius: 8rpx; } .cha{ z-index:3; width:30rpx; height:30rpx; position:absolute; right:0; }
.js代碼:
Page({ /** * 頁面的初始數據 */ data: { upload: true, files: [], sum: 0, }, // 上傳圖片 previewImage: function () { wx.chooseImage({ count: 1, sizeType: [‘compressed‘], // 可以指定是原圖還是壓縮圖,默認二者都有 sourceType: [‘album‘, ‘camera‘], // 可以指定來源是相冊還是相機,默認二者都有 success: (res) => { console.log(res) // 打印輸出返回值 let files = this.data.files files.push(res.tempFilePaths[0]) // 把圖片地址push到數組中 let sum = this.data.sum sum++ // 開始計數 this.setData({ sum: sum }) if (this.data.sum == 3) { // 如果sum==3隱藏上傳按鈕 this.setData({ upload: false }) } // 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標簽的src屬性顯示圖片 this.setData({ files: files }); } }) }, // 刪除圖片 delete: function (e) { let index = e.currentTarget.dataset.index let files = this.data.files files.splice(index, 1) this.setData({ files: files }) if (this.data.files.length == 0) { this.setData({ upload: true, sum: 0 }) } } })
微信小程序學習筆記五(持續更新)---小程序上傳文件