版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yhflyl/article/details/85060228
登录组件
组件的UI
<!--components/login/index.wxml-->
<button bind:getuserinfo="onGetUserInfo" open-type='{{openType}}' plain='{{true}}' class="container">
<slot name="img"></slot>
</button>
清除button的原始样式
.container{
padding: 0 !important;
border:none !important;
}
定义组件的事件
// components/login/index.js
Component({
// 开启使用插拔式的结点
options: {
multipleSlots: true
},
/**
* 组件的属性列表
*/
properties: {
openType:{
type: String
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
onGetUserInfo(event){
this.triggerEvent('getuserinfo', event.detail, {})
}
}
})
登录页面
使用登录组件
<view class="container">
<!-- 登录组件 -->
<img-btn-cmp wx:if="{{!hasUserInfo}}" open-type="getUserInfo" class="avatar-position" bind:getuserinfo="onGetUserInfo">
<image slot="img" class="avatar" src="/components/images/my.png" />
</img-btn-cmp>
<!-- 登录后使用open-data -->
<view class="avatar-container avatar-position">
<image src="{{userInfo.avatarUrl}}" wx:if="{{hasUserInfo}}" class="avatar" />
<open-data wx:if="{{hasUserInfo}}" type="userNickName"></open-data>
</view>
</view>
登录授权逻辑
// pages/me/me.js
Page({
/**
* 页面的初始数据
*/
data: {
hasUserInfo: false,
userInfo: null
},
onLoad: function() {
// 页面加载时使用用户授权逻辑,弹出确认的框
this.userAuthorized()
},
userAuthorized() {
wx.getSetting({
success: data => {
if( data.authSetting['scope.userInfo'] ){
wx.getUserInfo({
success: data => {
this.setData({
hasUserInfo: true,
userInfo: data.userInfo
})
}
})
}else{
this.setData({
hasUserInfo: false
})
}
}
})
},
onGetUserInfo(event) {
const userInfo = event.detail.userInfo
if (userInfo) {
wx.login({
success:function(res_1){
console.log(res_1)
wx.getUserInfo({
success: function(res_2) {
console.log(res_2)
// 发给服务器的数据
}
})
}
})
this.setData({
hasUserInfo: true,
userInfo: userInfo
})
}
}
})
wx.getSetting()回调函数返回数据
登录状态 | 图示 |
---|---|
登录 | |
未登录 |
wx.getUserInfo()回调函数返回数据
wx.login()函数返回值
接下就是后台接受处理请求。