微信小程序> 微信小程序笔记——小程序授权登录封装

微信小程序笔记——小程序授权登录封装

浏览量:474 时间: 来源:木子Leo

一、前言

产品需求:在游客模式登录下,用户做某些操作(如:评论,点赞。。。)时,需要拉起小程序授权登录,在没有单独登录页的情况下(为了方便可以让产品&UI出一个单独的登录页),封装一下小程序授权登录就比较方便了。

1、组件编写 

新建Component = author

author.wxml:

!-- 未登录情况下拉起授权登录按钮 --button class='author_btn' open-type='getUserInfo' bindgetuserinfo="bindGetUserInfo" lang='zh_CN' wx:if="{{!isAuthor}}"/button!-- 已登陆继续执行 --button class='author_btn' bindtap='goOn' wx:else/button

author.js:

// component/authorize.jsconst app = getApp();//apiimport requestApi from '../../utils/promiseRequestApi.js'Component({  properties: {},  data: {    isAuthor:false,//是否已授权  },  lifetimes: {    attached() {      this.setData({        isAuthor: app.globalData.isAuthor      })    }  },  methods: {    //已登陆    goOn(){      this.triggerEvent('flagEvent', {});    },    //授权    bindGetUserInfo(e){      let that = this;      if (e.detail.userInfo){        app.globalData.wxInfo = e.detail.userInfo;//用户微信信息        //获取登录信息(sessionkey,openid)        that.getLoginInfo();      }else{        console.log('用户点击了“拒绝授权”')      }    },    //获取登陆信息    getLoginInfo() {      let that = this;      wx.login({        success(res) {          if (res.code) {            requestApi('user/wxOpenIdDecode', 'POST', {              code: res.code            }).then((res) = {              app.globalData.sessionInfo = res.data;//用户sessionkey & openid              that.isLogin();            })          }        }      })    },    //登陆     isLogin(){      let that = this;       requestApi('user/login', 'POST', {        参数:''      }).then((res) = {        app.globalData.userInfo = res.data; //登录成功返回用户信息        app.globalData.isAuthor = true;        that.setData({          isAuthor:true        })        that.triggerEvent('flagEvent', {});//登录成功后继续执行      })    },      }})

author.wxss:

/*   利用定位 + z-index */.author_btn{  position: absolute;  top: 0;  left: 0;  width: 100%;  height: 100%;  border: none;  background-color: rgba(0, 0, 0, 0);  opacity: 0;  z-index: 2;}.author_btn::after{   border: none; } 

2、app.js公共变量存储

app.js = globalData:

globalData: {    isAuthor:false,//是否已授权    userInfo: null,//用户信息    wxInfo:null,//用户微信信息    sessionInfo:null,//用户sessionkey&openid    isIpx:false,//是否iphoneX  }

3、组件引用

json:{  "usingComponents": {    "isAuthor": "/components/author/author"  }}wxml:view class="likes"    image src='/images/like.png'/image    isAuthor bind:flagEvent="likesClick"/isAuthor/viewwxss:引用组件的父级配合组件进行定位,组件点击区域为引用组件父级宽高.likes {  position: relative;  width: 44rpx;  height: 44rpx;} js:  //点击事件 (登录后继续执行)  likesClick(){},

 

版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎