微信小程序模拟弹窗提示用户授权(wxss+wxml)
效果图:
wxml内容:
<!-- index.wxml -->
<view class="modal-box" hidden='{{!showTip}}'>
<view class="modal-content">
<view class="content-title">提示信息</view>
<view class="content-text">
绑定微信号需要收集您的部分用户信息,否则将无法绑定成功,请点击“确认”后按操作提示授权。
</view>
</view>
<view class="modal-btns">
<view class="weui-flex">
<view class="weui-flex__item">
<button class="dialog-btn cancel" bindtap="exit">取消</button>
</view>
<view class="weui-flex__item">
<button class="dialog-btn confirm" open-type="getUserInfo" bindgetuserinfo="getUserInfo">确认</button>
</view>
</view>
</view>
</view>
wxss内容(需要WeUI支持):
/** index.wxss **/
@import 'weui.wxss';
.modal-box {
position: fixed;
background: rgba(0, 0, 0, 0.4);
top: 0rpx;
width: 100%;
height: 100%;
}
.modal-content {
background: #fff;
width: 600rpx;
margin: 40% auto 0;
justify-content: center;
align-items: center;
border-bottom: 1px solid #ebebec;
}
.content-title {
height: 100rpx;
text-align: center;
font-size: 1.2rem;
padding-top: 10rpx;
}
.content-text {
padding: 0 50rpx 50rpx;
}
.modal-btns {
width: 600rpx;
margin: 0 auto;
justify-content: center;
align-items: center;
}
.dialog-btn {
border-radius: 0;
background: #fff;
height: 100rpx;
width: 100%;
}
.dialog-btn::after {
border: none;
border-radius: 0;
}
.cancel {
color: #ccc;
}
.confirm {
border-left: 1px solid #ebebec;
color: #60d048;
}
js牵扯的业务代码较多,不确定摘出来的这段代码是否完整,内容和官网DEMO相似,只是从app移到了index,主要目的是动态控制showTip变量实现提示框显示隐藏。
/* index.js */
var app = getApp();
Page({
data: {
canIUse: wx.canIUse('button.open-type.getUserInfo'),
showTip: false
},
onLoad: function (query) {
var self = this;
if (app.globalData.userInfo) {
console.log("用户已授权");
} else if (this.data.canIUse) {
console.log("请求用户授权");
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
// 登录
wx.login({
success: res => {
//console.log(res);
var code = res.code; //登录凭证
if (code) {
app.globalData.code = code;
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
//console.log(res);
app.globalData.userInfo = res.userInfo
app.globalData.encryptedData = res.encryptedData
app.globalData.iv = res.iv
if (res.userInfo) {
// 可以将 res 发送给后台解码出 unionId
} else {
self.setData({
showTip: true
});
}
}
})
} else {
self.setData({
showTip: true
});
}
},
fail: function () {
console.log('获取用户信息失败')
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
} else {
console.log("用户未授权");
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
}
})
}
},
getUserInfo: function(e) {
var self = this;
if (e && e.detail.userInfo) {
self.setData({
showTip: false
})
}
}
})