又到了一年一度的授权接口修改时间---ps.去年10月,希望今年能消停点。
话不多说上代码。
setName文件:<button class="avatar-wrapper" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar"> <image class="avatar" src="{{avatarUrl}}"></image> </button> <view class="form-box"> <form catchsubmit="formSubmit"> <view class="row"> <view class="text1">昵称:</view> <input type="nickname" bindinput="getName" class="weui-input" maxlength="16" minlength="2" name="input" placeholder="请输入2~16位昵称" value="{{nickName}}" /> </view> <button class="sub-btn" formType="submit">提交</button> </form> </view>
var api = require("/utils/api.js"), app = getApp() const defaultAvatarUrl = '/assets/person/head_portrait.png' Page({ data: { avatarUrl: defaultAvatarUrl, nickName: '', }, //选择图片 onChooseAvatar(e) { let that = this wx.getFileSystemManager().readFile({ filePath: e.detail.avatarUrl, //地址 encoding: 'base64', //编码格式 success: res => { let base64 = 'data:image/png;base64,' + res.data that.setData({ avatarUrl : base64 }) } }) }, //获取昵称 getName(e) { let nick_name = e.detail.value this.setData({ nickName: nick_name }) }, //提交 formSubmit(e) { let that = this let openId = wx.getStorageSync("openId") let nickName = that.data.nickName.trim() let avatarUrl = that.data.avatarUrl if(avatarUrl == defaultAvatarUrl){ wx.showToast({ title: '请选择头像', icon: 'none' }) return; }else if(nickName.length==''){ wx.showToast({ title: '昵称不能为空', icon: 'none' }) return; }else if((/[^/a-zA-Z0-9\u4E00-\u9FA5]/g).test(nickName)){ wx.showToast({ title: '昵称不合法', icon: 'none' }) return; } app.request({ url: XXX, method: "POST", data:{ openId, nickName, headPortraitBase64:avatarUrl }, success: function (res) { wx.showToast({ title: '修改成功!', }) let userInfo = { nickName:res.Resultes.XXX, avatarUrl:res.Resultes.XXX.replace(/\\/g,"/") } wx.setStorage({ key: 'userInfo', data: userInfo, success: function() { console.log('保存成功') wx.switchTab({ url: '/pages/person/person', }) }, fail: function() { } }) }, fail: function() { wx.showToast({ title: '修改失败!', icon: 'none' }) } }) }, })
.avatar-wrapper { padding: 0; width: 125rpx; height: 125rpx; border-radius: 50%; margin-top: 40px; margin-bottom: 40px; } .avatar { display: block; width: 125rpx; height: 125rpx; border-radius: 50%; } .container { display: flex; } .form-box{ width: 690rpx; margin: 0 auto; } .row{ display: flex; align-items: center; border-top: 1px solid #f4f4f4; border-bottom: 1px solid #f4f4f4; padding: 30rpx 0 35rpx 0; margin-bottom: 120rpx; } .weui-input{ width: 500rpx; } .sub-btn{ color: #fff; background-color: blue; }
person文件: 注:要在生命周期onShow中获取数据。
onShow: function () { let that = this wx.getStorage({ key: 'userInfo', success: function (res) { that.setData({ userInfo: res.data }) }, }) },
标签:缓存,avatarUrl,微信,昵称,data,let,res,nickName,wx From: https://www.cnblogs.com/bk1234/p/17400974.html