一、简介:
小程序一开始进入首页,进入后判断是否登录,如未登录自行跳转到授权登录页面,登录后再到首页。
二、项目目录:
三、代码:
app.js:
将代码放入onLaunch函数中,如有wx.getSetting直接替换
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
} else {
// 未授权,跳转到授权页面
wx.reLaunch({
url: '/pages/login/login',
})
}
}
})
login.wxml:
<!--pages/login/login.wxml-->
<view class="content">
<view class='img'>
<open-data type='userAvatarUrl' class='Avatar'></open-data>
</view>
<view class="title">微信授权页面</view>
<view class="tishi">此页面是微信授权页面,点击下方按钮弹出授权或跳转页面</view>
<button class="btn" open-type='getUserInfo' bindgetuserinfo='onAuth'>微信授权登录</button>
</view>
## login.wxss:
/* pages/login/login.wxss */
page {
height: 100%;
background-color: rgba(217, 255, 255, 0.63);
}
.content {
margin-top: 0;
text-align: center;
display: table-cell;
flex-direction: column;
flex-wrap: wrap;
justify-content: center;
align-items: flex-start;
padding: 100rpx;
vertical-align: middle;
}
.Avatar {
overflow:hidden;
border-radius: 50%;
border: 1px solid #fff;
background-color: #fff;
margin: 0 0 60rpx;
display: inline-block;
width: 200rpx;
height: 200rpx;
}
.title {
display: inline-block;
width: 100%;
margin: 0 0 60rpx;
}
.tishi {
color: #a7aaa9;
font-size: 26rpx;
margin: 0 0 60rpx;
border-radius: 50%;
text-align: center;
display: inline-block;
width: 100%;
}
.btn {
padding: 0 60rpx;
background-color: #19be6b;
margin: 20rpx 0 ;
text-align: center;
vertical-align: middle;
touch-action: manipulation;
cursor: pointer;
background-image: none;
white-space: nowrap;
user-select: none;
font-size: 14px;
border: 0 !important;
position: relative;
text-decoration: none;
height: 44px;
line-height: 44px;
box-shadow: inset 0 0 0 1px #19be6b;
background: #fff !important;
color: #19be6b !important;
display: inline-block;
border-radius: 10rpx;
}
login.js:
// pages/login/login.js
var app = getApp();
Page({
data: {
},
onAuth() {
wx.getSetting({
success: (res) => {
if (res.authSetting['scope.userInfo']) {//判断是否授权
wx.reLaunch({//跳转到首页
url: '../index/index',
})
}
}
})
}
})