效果图:
代码:
login.wxml
<navbar navbar-data='{{navbarData}}'></navbar>
<view class="userinfo">
<block wx:if="{{userInfo==null}}">
<image bindtap="bindViewTap" class="userinfo-avatar" src="https://img2.baidu.com/it/u=3871105402,2821163553&fm=253&fmt=auto&app=138&f=JPEG?w=300&h=300" mode="cover"></image>
<text class="userinfo-nickname">Default Avatar</text>
</block>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
<view class="content">
<block wx:if="{{userInfo==null}}">
<view>申请获取以下权限</view>
<text>获得你的公开信息(昵称,头像等)</text>
<button class='bottom' type='primary' lang="zh_CN" bindtap="getUserProfile">
授权登录
</button>
</block>
<block wx:else>
<van-cell-group>
<van-field
value="{{ username }}"
required
clearable
label="手机号"
icon="phone-o"
placeholder="请输入手机号"
bind:blur="OnChangeTel"
title-width="4.5em"
/>
</van-cell-group>
<button class='bottom' type='primary' lang="zh_CN" bindtap="confirm">
确认
</button>
</block>
<van-notify id="van-notify" />
</view>
login.wxss
.userinfo {
width: 85%;
border-bottom: 1px solid #d2d2d2;
color: #aaa;
text-align: center;
padding: 70rpx 0;
margin: 0 auto;
}
.userinfo-avatar {
width: 200rpx;
height: 200rpx;
}
.userinfo-nickname {
display: block;
color: black;
margin-top: 40rpx;
}
.content {
text-align: center;
padding: 50rpx 50rpx 90rpx 60rpx;
}
.content text {
display: block;
color: #9d9d9d;
margin-top: 40rpx;
}
.bottom {
border-radius: 80rpx;
font-size: 36rpx;
margin-top: 130rpx;
}
login.js(授权逻辑)
import Notify from '@vant/weapp/notify/notify'
import api from '../../api/api.js'
import { decodeUserInfo } from '../../api/index.js'
var app = getApp()
Page({
data: {
navbarData: { title: '授权登录' },
userInfo: app.globalData.userInfo,
openId: app.globalData.openId,
},
onLoad() {
//获取 userInfo
let user = wx.getStorageSync('userInfo')
this.setData({ userInfo: user })
},
//获取头像和昵称
getUserProfile(e) {
const that = this
wx.getUserProfile({
desc: '业务需要',
success: res => {
let user = res.userInfo
//存储 userInfo
wx.setStorageSync('userInfo', user)
this.setData({ userInfo: user })
//通过wx.login获取登录凭证(code),然后通过code去获取我们用户的openid
wx.login({
desc: '正在获取',
success: res => {
const code = res.code
//这里的decodeUserInfo是后端的接口地址
api.get(decodeUserInfo + '?code=' + code).then(res => {
let openId = res.data.openid
//存储openId
wx.setStorageSync('openId', openId)
this.setData({ openId: openId })
}).catch(err => {
Notify({
type: 'danger',
message: err.msg,
safeAreaInsetTop: true,
duration: 4000
})
})
}
})
}
})
}
})