wxml
<view class="container">
<view class="weui-uploader">
<view class="img-v weui-uploader__bd">
<view class='pic' wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
<image class='weui-uploader__img ' src="{{item}}" data-index="{{index}}" mode="aspectFill" bindtap="previewImg">
<icon type='cancel' class="delete-btn" data-index="{{index}}" catchtap="deleteImg"></icon>
</image>
</view>
<!-- 用来提示用户上传图片 -->
<view class="weui-uploader__input-box pic" bindtap="chooseImg"></view>
</view>
<button class="upload-img-btn" bindtap="chooseImg" data-name="imgss" data-num="1"
type='primary'>拍照 / 上传</button>
</view>
</view>
CSS
.pic {
float: left;
position: relative;
margin-right: 9px;
margin-bottom: 9px;
}
.delete-btn {
position: absolute;
top: 0;
right: 0;
}
.weui-uploader {
padding: 10rpx;
}
JS
//获取应用实例
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {// 组件所需的参数
imgs: [],
},
// 上传图片
chooseImg: function (e) {
var _this = this;
var imgs = _this.data.imgs;
var imgName = e.currentTarget.dataset.name;
var limit = e.target.dataset.num;
var data = this.data[imgName];
if (data.length >= limit) {
wx.showToast({
title: '只能上传' + limit + '张',
icon: 'none'
});
return false;
}
wx.chooseImage({
// count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths;
var imgs = _this.data.imgs;
// console.log(tempFilePaths + '----');
for (var i = 0; i < tempFilePaths.length; i++) {
if (imgs.length >= 9) {
_this.setData({
imgs: imgs
});
return false;
} else {
imgs.push(tempFilePaths[i]);
}
}
// console.log(imgs);
_this.setData({
imgs: imgs
});
}
});
},
// 删除图片
deleteImg: function (e) {
var imgs = this.data.imgs;
var index = e.currentTarget.dataset.index;
imgs.splice(index, 1);
this.setData({
imgs: imgs
});
},
// 预览图片
previewImg: function (e) {
//获取当前图片的下标
var index = e.currentTarget.dataset.index;
//所有图片
var imgs = this.data.imgs;
wx.previewImage({
//当前显示图片
current: imgs[index],
//所有图片
urls: imgs
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})