微信小程序之getUserInfo loading登录页分享

因为微信修改了接口,此为本人最新使用方案
TIM截图20180604042327.jpg

wxss

.loading_tip{
  position: fixed;
  height: 100%;
  width: 100%;
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content: center;
  font-size: 1rem
}

wxml

<view class="container">
  <view class="loading_tip ">
    <view>登录后体验完整功能</view>
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo" type="primary">点此登录</button>
  </view>
</view>

js

var app = getApp()

Page({
    data: {
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
    },

    onLoad: function (options) {
        if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = e => {
                this.login(e);
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: e => {
                    this.login(e);
                }
            })
        }
    },
    getUserInfo: function (e) {
        this.login(e.detail);
    },
    login: function (e) {
        var that = this
        wx.login({
            success: function (res) {
                app.post({//封装的post方法
                    url: 'my/index/login',
                    data: { code: res.code, encryptedData: e.encryptedData, iv: e.iv },
                    success: function (res) {
                        app.globalData.userInfo = e.userInfo
                        wx.setStorageSync('userInfo', e.userInfo)//将userInfo存入缓存
                        var pages = getCurrentPages();
                        var prevPage = pages[pages.length - 2];  //上一个页面
                        prevPage.onLoad(prevPage.options)//重载上个页面
                        wx.navigateBack()//返回上一页
                    }
                });
            }
        })
    }
})