Wechat applet-修改学员头像
实现效果:点击头像,重新上传新头像;上传成功后,点击头像,可再次重新上传头像。☺️
对应代码:
wxml
<view class="imgBox">
<van-uploader class="vanUploader" max-size="{{maxSize}}" bind:oversize="file_oversize" bind:after-read="afterRead" max-count="1" />
<image class="children_avatar" src="{{publicData.thumb_tmp}}"></image>
</view>
wxss
【重要】
.imgBox {
position: relative;
width: 132rpx;
height: 132rpx;
border-radius: 50%;
margin-right: 32rpx;
overflow: hidden;
}
.children_avatar {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
left: 0;
top: 0;
}
.imgBox .vanUploader {
opacity: 0;
z-index: 99;
}
js
Page({
/**
* 页面的初始数据
*/
data: {
_ID: '',
publicData: '',
fileList: [],
maxSize:3*1024*1024, // 头像的最大文件范围
},
// 请求接口-修改学员头像
editThumb() {
let that = this;
let params = {
cid: that.data._ID,
thumb: that.data.fileList[0].url
}
editThumbApi(params)
.then(res => {
if(res) {
if(res.sta == 2000) {
this.setData({
['publicData.thumb_tmp']:params.thumb, // 切换展示的头像
})
Toast(res.msg)
} else {
Toast(res.msg)
}
} else {
Toast('请求失败,请稍后再试')
}
})
},
// 上传头像
afterRead(event) {
let that = this;
const {file} = event.detail;
let urlArr = [];
// console.log(file);
// file.map((item, index) => {
uploadImage(file.url, '', function (res) {
urlArr.push({
name: 'img',
url: res
});
let myFileList = [{url:res}];
that.setData({
fileList: myFileList,
})
that.editThumb();
}, function (err) {
Toast('上传失败,请稍后再试');
})
// })
},
// 上传的图片超出大小限制
file_oversize() {
Toast('上传的图片需限制在3M以内')
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData() {
_ID: options.id,
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})