例如点击某个底部菜单需要用户授权才能访问,或者是进入小程序的时候就需要用户授权。
思路大概如下,例如点击新闻导航,需要用户授权后才能访问,在news页面的onLoad生命周期写入:
wx.getSetting({ success(res) { if (res.authSetting['scope.userInfo']) { wx.getUserInfo({ success: (res) => { //这里是获取用户的信息 } }) } else { //如果没有授权就跳转到授权页面 wx.reLaunch({ url: '/pages/auth/auth', }) } } })
这段逻辑是当用户进入这个页面使用小程序提供的getSetting,如果已经授权返回信息中会携带authSetting.scope.userInfo为true,根据这个判断用户是否授权,没有授权就执行了else里面的代码,跳转授权页面
在page下面新建auth目录,auth.wxml代码如下:
<view class="auth"> <image src="https://res.wx.qq.com/wxopenres/htmledition/images/favicon32f740.ico" class="img" mode="aspectFill"></image> <view class="title">微信授权页面</view> <view class="describe">此页面是微信授权页面,点击下方按钮弹出授权或跳转页面</view> <button class="btn" open-type='getUserInfo' wx:if="{{canIUse}}" bindgetuserinfo='onAuth'>点击微信授权</button> </view>
auth.wxss代码
/* 开始 */ page { height: 100%; display: table; } .auth { 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; } .img { border-radius: 50%; border: 1px solid #fff; background-color: #fff; margin: 0 0 60rpx; display: inline-block; width: 200rpx; height: 200rpx; line-height: 0; } .title { display: inline-block; width: 100%; margin: 0 0 60rpx; } .describe { 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 200rpx; 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; }
auth.js代码
Page({ data: { canIUse: wx.canIUse('button.open-type.getUserInfo') }, onLoad() { }, onAuth() { wx.getSetting({ success: (res) => { if (res.authSetting['scope.userInfo']) { wx.reLaunch({ url: '/pages/book/book', }) } else { wx.showToast({ title: '拒绝将无法访问此页面', icon: 'waiting' }) } }, fail: (err) => { console.log(err) } }) } })
当用户点击了授权后跳转相关页面
wx.getSetting
获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
wx.canIUse(string schema)
判断小程序的API,回调,参数,组件等是否在当前版本可用。
// 对象的属性或方法 wx.canIUse('console.log') wx.canIUse('CameraContext.onCameraFrame') wx.canIUse('CameraFrameListener.start') wx.canIUse('Image.src') // wx接口参数、回调或者返回值 wx.canIUse('openBluetoothAdapter') wx.canIUse('getSystemInfoSync.return.safeArea.left') wx.canIUse('getSystemInfo.success.screenWidth') wx.canIUse('showToast.object.image') wx.canIUse('onCompassChange.callback.direction') wx.canIUse('request.object.method.GET') // 组件的属性 wx.canIUse('live-player') wx.canIUse('text.selectable') wx.canIUse('button.open-type.contact')
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接