在小程序开发中,受权登陆是最多见的操做,由于不少业务是要求用户登陆以后才能进行操做,那么这个流程我是怎么设计的呢,下面我就给你们唠一唠。javascript
由于受权操做属于比较基本的功能,并且公共需求比较高,因而我把它放到了 app.js
中。在须要的地方,经过 getApp()
函数拿到 app 实例进行调用便可,使用上仍是比较便利的。css
下面是 app.js
中核心的代码片断:html
{
/** * 封装一个函数统一获取用户信息,避免直接操做 globalData */
getUserInfo() {
return this.globalData.userInfo;
},
/** * 判断是否登陆 */
checkAuth() {
return new Promise((resolve, reject) => {
const userInfo = this.getUserInfo();
userInfo ? resolve(userInfo) : reject('未登陆');
});
},
/** * 受权登陆 * 我为了简单直接用 wx.getUserProfile 进行模拟受权 * 实际的业务状况可能还须要弹出个面板或者跳转到受权页面之类的 */
auth() {
return new Promise((resolve, reject) => {
wx.getUserProfile({
desc: '受权登陆',
success: resolve,
fail: reject,
})
}).then(({ userInfo }) => {
this.globalData.userInfo = userInfo;
});
},
/** * 保证必定是登陆的状态 */
authed() {
return this.checkAuth().catch(() => {
return this.auth();
});
},
/** * 退出登陆 */
logoff() {
return new Promise((resolve) => {
this.globalData.userInfo = null;
resolve();
});
},
globalData: {
userInfo: null
}
}
复制代码
主要的逻辑函数都用流行的 Promise 包裹,避免回调嵌套,组合使用特方便。在实际的业务中我会这样去使用:java
{
// tap事件处理
async clickHandler() {
const app = getApp();
// 点击以后,经过 authed() 函数保证用户必定是登陆状态
// 通 Promise 链,能够很容易的实现受权以后,自动执行后续的流程
app.authed().then(() => {
// 身份校验经过后调用核心的逻辑 actAction
return this.actAction();
});
},
async actAction() {
// todo 动做响应
console.log('动做响应');
}
}
复制代码
经过 js
的方式,这样没问题,但我想 Amazing
一下:我能不能在 js
中不调用 authed()
也能实现同样的逻辑 。通过我 3S
钟的思考以后,一激动就拔下了名叫 Tom 的这根头发:git
对于有点击行为的元素,我能够设计一个
Auth
组件,专门用来作登陆操做,而后将这个组件嵌套在须要有点击行为的元素中。github好比:小程序
<button class="submit-btn" bindtap="actAction">点击<Auth/></button> 复制代码
让这个
Auth
像玻璃同样填充满父容器,阻止掉Auth
组件冒泡的tap
事件。当点击的时候实际上会先触发Auth
组件的tap
事件,父容器的tap
事件并不会触发。在Auth
组件中完成受权后,再抛出自定义的tap
事件,父容器的tap
事件触发,actAction
函数调用成功!很是完美markdown
因而在我飞快的手速下,核心的代码也逐渐清晰了起来,键盘彷佛也有了点儿糊味,哦!原来是 Tom 烧焦了~app
Auth 组件的核心代码以下:dom
模版:
<-- catchtap 特别重要,这样能够捕获到点击,而且阻止冒泡给外层 -->
<view class="layer" catchtap="authCheckHandler" style="z-index:{{zIndex}};"></view>
复制代码
样式表:
.layer {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
复制代码
JS 部分:
Component({
properties: {
zIndex: {
type: Number,
value: 10
}
},
methods: {
authCheckHandler() {
const app = getApp();
app.authed().then(() => {
this.successHandler();
});
},
successHandler() {
// 触发 tap 事件
this.triggerEvent('tap', {}, {
bubbles: true, // @IMPORTANT 这个地方重要的配置,容许自定义事件冒泡
});
},
closeHandler() {
// 关闭受权弹窗
this.setData({
visible: false,
});
}
},
});
复制代码
详细的代码我放在 wx-auth-demo 这个项目中,感兴趣的同窗能够下载体验一下。核心的点就是经过 dom 嵌套 + 事件冒泡
,来替换 js
逻辑中的嵌套,接下来我仍是要给本身鼓会儿掌~