在开发发表日志、博客之类的功能时,往往用到上传组件上传一张或者多张图片,功能需求及效果图如下:
效果图:
需求:
在点击上传标志时,可以选择拍照或者手机相册上传,点击右上角的删除按钮,可以删除当前上传的图片。
代码分析
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表示预览图片。