1.template标签里至少有一个button标签
<button open-type="openSetting" @opensetting="onGetLocation">立即授权</button>
open-type以及按钮事件可以有其他搭配,比如getUserInfo及@getuserinfo
2.js中添加判断
当程序需要某些数据的时候,例如地理位置,这种敏感的数据往往用户反手就是一个拒绝…为了更好的用户体验咱先不进入页面就申请,等用户在页面有所操作再请求获取权限。api来自uni-app框架,wx开发的直接将uni换成wx便可。
if(数据不够用了) {
uni.getSetting({
success:(res) => {
if (!res.authSetting['scope.userLocation']) {
console.log('userLocation-error');
wx.authorize({
scope: 'scope.userLocation',
success:() => {
//用户第一次进来并且直接就同意了
//用户开启了权限,直接开始业务
},
fail:() => {
console.log('authorize-error');
//点亮button
}
})
} else {
// 用户开启了权限,直接开始业务
}
}
})
} else {
//已有的数据够用了,直接开始业务
}
按钮事件如下
onGetLocation(e){
if(e.detail.authSetting['scope.userLocation']){
// 隐藏按钮
// 用户终于开启了权限,可以开始业务了
} else {
// 用户还是没有开我要的权限,授权按钮不隐藏
}
}