想要获取用户信息需要先使用wx.login功能
wx.login({ success: res => { if (res.code) { // 获取 code 成功后,通过微信开放接口获取用户 openid wx.request({ url: '后台接口', data: { code: res.code, }, success: res => { console.log(res.data.openid); this.openid = res.data.openid uni.setStorageSync('openid', res.data.openid) } }); } }, fail: err => { console.log(err); } });
然后使用按钮的open-type获取用户的头像,想要获取完整用户信息可以使用getUserInfo
<view class=""> // 调用微信开放能力 <button open-type="chooseAvatar" @chooseavatar="chooseAvatar" style="width:190rpx;height: 190rpx;border-radius: 50%;padding: 0;margin-top: 20px;"> <image :src="image" class="imageAsdf" style="width: 200rpx;height: 200rpx;border-radius: 100%;" /> </button> </view>
获取用户昵称
<view style="width: 60%;margin: auto;margin-top: 10px;"> <input id="nickname-input" v-model="nickname" class="authorization white" type="nickname" placeholder="请输入用户昵称" style="width: 100%;text-align: center;" @change="change"> </view>
保存头像和昵称
change(e) { this.nickname = e.detail.value }, chooseAvatar(e) { console.log(e); this.image = e.detail.avatarUrl },
登录判断:
// 登录 logins() { let that = this; if (that.nickname == '') { uni.showToast({ icon: 'none', title: '请输入用户昵称', // duration: 2000 }); } else if (that.image == '') { uni.showToast({ icon: 'none', title: '请上传用户头像', // duration: 2000 }); } if (that.nickname != '' && that.image != '') { uni.request({ url: '登录接口', //参数 data: { openid: that.openid, value:value }, dataType: 'json', method: "POST", success(res) { console.log(res); if (res.data.err == '请求成功') { console.log(res.data.userid); uni.setStorageSync('userid', res.data.userid); uni.showToast({ title: '登录成功', duration: 2000 }); // 跳转路径 let path = uni.getStorageSync('paths'); setTimeout(() => { uni.reLaunch({ url:`/pages/${path}/${path}` }) }, 2000) } else { uni.showToast({ title: '登录失败', icon:'none', duration: 2000 }); } } }) } }