前言
最近微信获取用户信息的接口有调整,就是这货:wx.getUserInfo(OBJECT),文档描述如下:
此接口有调整,使用该接口将不再出现授权弹窗,请使用 <button open-type="getUserInfo"></button> 引导用户主动进行授权操作1.当用户未授权过,调用该接口将直接报错2.当用户授权过,可以使用该接口获取用户信息
这就很蛋疼了,以前只需要弹框授权就行了,现在还必须要先按一个按钮,这样的话多了一个操作,多一个按钮感觉很别扭,放在页面上哪里都不合适,
看评论区有个图亮了:
解决方案
无缘无故在页面上多了一个按钮,只是为了引导用户授权,加在哪里都会觉得和页面内容格格不入。
那就弹一个框提示吧,虽然连续两个弹框也很怪,但是个人觉得比页面多一个按钮好一点。
微信自己定义的弹框交互并不适合授权这个场景,那就想到自定义一个弹框组件来解决。
实现
新建 components 目录文件如下:
dialog.json 文件内容:
{"component": true, // 自定义组件必须先声明"usingComponents": {}
}
dialog.js 文件内容:
Component({options: {multipleSlots: true // 在组件定义时的选项中启用多slot支持},/*** 组件的属性列表*/properties: {// 弹窗标题title: { type: String, value: '标题' // 默认值},// 弹窗内容content :{type : String ,value : '弹窗内容'},// 弹窗确认按钮文字confirmText :{type : String ,value : '确定'} },/*** 组件内私有数据*/data: {// 弹窗显示控制isShow:false},/*** 组件的公有方法列表*/methods: {//隐藏弹框hideDialog(){this.setData({isShow: !this.data.isShow})},//展示弹框showDialog(){this.setData({isShow: !this.data.isShow})},/*** triggerEvent 组件之间通信*/confirmEvent(){this.triggerEvent("confirmEvent");},bindGetUserInfo(){this.triggerEvent("bindGetUserInfo");}}
})
dialog.wxml 文件内容:
<view class='dialog-container' hidden="{{!isShow}}"><view class='dialog-mask'></view><view class='dialog-info'><view class='dialog-title'>{{ title }}</view><view class='dialog-content'>{{ content }}</view><view class='dialog-footer'><button class='dialog-btn' open-type="getUserInfo" bindgetuserinfo='bindGetUserInfo' catchtap='confirmEvent'>{{ confirmText }}</button></view></view>
</view>
dialog.wxss 文件内容:
.dialog-mask{position: fixed;z-index: 1000;top: 0;right: 0;left: 0;bottom: 0;background: rgba(0, 0, 0, 0.3);
}
.dialog-info{position: fixed;z-index: 5000;width: 80%;max-width: 600rpx;top: 50%;left: 50%;-webkit-transform: translate(-50%, -50%);transform: translate(-50%, -50%);background-color: #FFFFFF;text-align: center;border-radius: 3px;overflow: hidden;
}
.dialog-title{font-size: 36rpx;padding: 30rpx 30rpx 10rpx;
}
.dialog-content{padding: 10rpx 30rpx 20rpx;min-height: 80rpx;font-size: 32rpx;line-height: 1.3;word-wrap: break-word;word-break: break-all;color: #999999;
}
.dialog-footer{display: flex;align-items: center;position: relative;line-height: 90rpx;font-size: 34rpx;
}
.dialog-btn{display: block;-webkit-flex: 1;flex: 1;position: relative;color: #3CC51F;
}
在首页或者我的页面进行授权检测:
首先还是要在 json 文件进行声明
index.json:
{"usingComponents": {"dialog": "/components/dialog/dialog"}
}
index.wxml:
<dialog id='dialog' title='登录提示' content='小程序需要您的授权才能提供更好的服务哦' confirmText='知道了'bind:confirmEvent='confirmEvent'bind:bindGetUserInfo='bindGetUserInfo'>
</dialog>
index.js:
onReady: function () {//获得dialog组件this.dialog = this.selectComponent("#dialog");
},showDialog: function(){this.dialog.showDialog();
},confirmEvent: function(){this.dialog.hideDialog();
},bindGetUserInfo: function() {// 用户点击授权后,这里可以做一些登陆操作this.login();
},
效果
总结
参考:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/