在開發發表日誌、博客之類的功能時,往往用到上傳組件上傳一張或者多張圖片,功能需求及效果圖如下:
效果圖:
需求:
在點擊上傳標誌時,可以選擇拍照或者手機相冊上傳,點擊右上角的刪除按鈕,可以刪除當前上傳的圖片。
代碼分析
HTML
<view class="uni-list list-pd">
<view class="uni-list-cell cell-pd">
<view class="uni-uploader">
<view class="uni-uploader-head">
<view class="uni-uploader-title">點擊可預覽選好的圖片</view>
<view class="uni-uploader-info">{{imageList.length}}/9</view>
</view>
<view class="uni-uploader-body">
<view class="uni-uploader__files">
<block v-for="(image,index) in imageList" :key="index">
<view class="uni-uploader__file">
<view class="icon iconfont icon-shanchu" @tap="delect(index)"></view>
<image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
</view>
</block>
<view class="uni-uploader__input-box">
<view class="uni-uploader__input" @tap="chooseImage"></view>
</view>
</view>
</view>
</view>
</view>
</view>
JS
<script>
var sourceType = [
['camera'],
['album'],
['camera', 'album']
]
var sizeType = [
['compressed'],
['original'],
['compressed', 'original']
]
let changelook = ['所有人可見', '僅自己可見'];
import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue'
export default {
components: {
uniNavBar,
},
data() {
return {
text:'66666',
yinsi: '所有人可見',
imageList: [],
sourceTypeIndex: 2,
sourceType: ['拍照', '相冊', '拍照或相冊'],
sizeTypeIndex: 2,
sizeType: ['壓縮', '原圖', '壓縮或原圖'],
countIndex: 8,
count: [1, 2, 3, 4, 5, 6, 7, 8, 9]
}
},
methods: {
back() {
uni.navigateBack({
delta: 1
});
},
submit() {
console.log('發佈');
},
changeLook() {
uni.showActionSheet({
itemList: changelook,
success: (res) => {
console.log(res);
console.log('選中了第' + (res.tapIndex + 1) + '個按鈕');
this.yinsi = changelook[res.tapIndex];
},
fail: (res) => {
console.log(res.errMsg);
}
});
},
// 選擇圖片
chooseImage: async function() {
if (this.imageList.length === 9) {
return;
}
uni.chooseImage({
sourceType: sourceType[this.sourceTypeIndex],
sizeType: sizeType[this.sizeTypeIndex],
count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length :
this.count[this.countIndex],
success: (res) => {
this.imageList = this.imageList.concat(res.tempFilePaths);
console.log(this.imageList.length,'照片數量')
}
})
},
previewImage: function(e) {
var current = e.target.dataset.src
uni.previewImage({
current: current,
urls: this.imageList
})
},
delect(index){
uni.showModal({
title: '提示',
content: '是否刪除該圖片?',
success: (res) =>{
if (res.confirm) {
this.imageList.splice(index, 1)
}
}
});
}
}
}
</script>
代碼分析:
1、變量sourceType、sizeType分別表示照片來源(拍照或者相冊)與照片大小處理方式(原始或者壓縮)。
2、chooseImage表示選擇照片,previewImage表示預覽圖片。