名为最佳,实则不敢自称为最佳,因为代码永远没有最佳,只有最佳。小生不才,很少分享代码,因为代码可以实现的方法万万千千,同一个功能,不同的各种场景使用哪种代码方式也是各有不同。所以代码只有适合自己的,没有敢自称最佳的代码。
但是,一般来讲实现的逻辑有最好的。实现的逻辑思维比写代码重要得多,今天分享的其实是一个升级的逻辑思路。优雅简便的升级逻辑思路。大家可以参考:
做微信小程序的老铁都知道4.13号开始wx.getUserProfile要正式上线了,很多老的项目需要修改登陆逻辑,如何最简单的,代码改动最小的方式修改代码来实现新旧版本兼容,优雅的完成升级呢?一起来看看下面的一个方案:
先简单介绍下这个升级方案的逻辑吧:
wxml文件改造:
新增个getUserProfile的微信登陆入口。使用canIUseGetUserProfile来判断是使用旧版getUserInfo还是新的getUserProfile方式获取用户信息。
JS改造:
1、把旧的登陆逻辑代码单独出来一个doLogin方法,同时加以改造,新增个proFileUserInfo参数接收已经通过getUserProfile获取到的用户信息。如果这个参数有值的情况下优先使用这里面的已经获得到用户信息!
2、新增个登陆中间件方法wxLogin方法来接收wxml里的微信登陆按钮bindtap事件。并通过判断是canIUseGetUserProfile的值来调用getUserProfile还是getUserInfo方式来获取用户信息,再传递给doLogin方法。
下面是部分代码参考:
wxml:
- <button class="weui-btn txwb-main-bg" type="warn" bindtap="wxLogin" wx:if="{{canIUseGetUserProfile}}"> <span class="iconfont icon-txwb-weixin" style="margin-right:10rpx;"></span>
- 微信授权登陆
- </button>
- <button class="weui-btn txwb-main-bg" type="warn" open-type='getUserInfo' bindgetuserinfo="wxLogin" wx:else> <span class="iconfont icon-txwb-weixin" style="margin-right:10rpx;"></span> 微信授权登陆
- </button>
复制代码
js:
- data: {
- ....
- canIUseGetUserProfile: false,
- ....
- }
-
- onLoad(options){
- ...
- if (wx.getUserProfile) {
- this.setData({ canIUseGetUserProfile: true });
- }
- ...
- }
-
- wxLogin(e){//新增的一个登陆中间方法
- var that = this;
- wx.showLoading({
- title: '正在登陆..', //提示的内容,
- mask: true, //显示透明蒙层,防止触摸穿透,
- success: res => { }
- });
- if (this.data.canIUseGetUserProfile) {
- wx.getUserProfile({
- desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
- success: (res) => {
- that.doLogin(e, res.userInfo);
- },
- fail: res => {
- console.log("logwxloginres", res);
- wx.hideLoading();
- }
- });
- } else {
- that.doLogin(e);
- }
- }
-
- doLogin(e, proFileUserInfo = null){//旧的登陆代码
- ...
- //原来的登陆代码逻辑,在旧的getUserInfo代码处新增判断:
- wx.getUserInfo({
- success: function (res) {
- /* begin 下面3行是新增的判断,代表userInfo已经通过wx.getUserProfile获取过获取过*/
- if (proFileUserInfo) {
- res.userInfo = proFileUserInfo;
- }
- /* end */
- }
- });
- ...
- }
复制代码
|