溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在微信小程序中監(jiān)聽用戶登錄事件

發(fā)布時間:2021-04-17 17:04:47 來源:億速云 閱讀:646 作者:Leah 欄目:web開發(fā)

本篇文章給大家分享的是有關(guān)怎么在微信小程序中監(jiān)聽用戶登錄事件,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

需求如下:

  • 小程序共三個tab頁,所有用戶都可以瀏覽首頁內(nèi)容,了解我們可以提供的優(yōu)質(zhì)服務;

  • 進入其他兩個頁面之后,如果用戶沒有登錄,那就顯示登錄按鈕,如果登錄了,則顯示服務內(nèi)容;

  • 用戶在一個頁面登陸之后,全局生效。

就這么個看起來很簡單的需求,也經(jīng)過了如下迭代:

  • 將登錄狀態(tài)和憑據(jù)存儲在 App.globalData.authorize 中,每個需要授權(quán)的頁面 onload 生命周期檢查 App.globalData.authorize.authorized ,為 true 時渲染服務內(nèi)容,為 false 則顯示登錄按鈕;

  • 但如果打開了需要授權(quán)的頁面 A 但是沒有登錄,再打開頁面 B 登錄,這時候回到 A 頁面,登錄按鈕赫然在眼,這是因為 A 頁面的 onload 回調(diào)函數(shù)只執(zhí)行了一次;

  • 為了能在 A 頁面及時共享 B 頁面登錄后的狀態(tài),在 A 頁面的 onshow 生命周期里再獲取了一次登錄狀態(tài),但這樣一來,打開 A 頁面的時候,會出現(xiàn)短暫的白屏,用戶甚至有可能看到按鈕變成服務內(nèi)容的整個過程。

翻遍小程序 API 文檔 ,也沒有發(fā)現(xiàn)用于監(jiān)聽登錄的生命周期,就算有也用不了,因為我們有著自己的賬號體系,服務端認證完畢才算真正的登錄成功。

所以我決定自己包裝原有的 Page 函數(shù),添加一個 onauth 生命周期——

首先是自定義登錄事件的觸發(fā)與監(jiān)聽,官方的EventChannel 需要向后兼容,橫豎是個訂閱回調(diào),那我還不如自己擼一個得了:

/**
 * @file utils/event.js
 */

/**
 * @const EMPTY_HANDLER
 * @desc 空事件回調(diào),被取消事件將被指向此函數(shù)
 */
const EMPTY_HANDLER = () => {};

/**
 * @const eventSet - 事件監(jiān)聽函數(shù)集
 */
const eventSet = {
 authorize: []
};

/**
 * @function emit - 發(fā)送全局事件
 * @param {String} type - 事件類型
 * @param {Object} event - 事件對象
 */
export const emit = (type, event) => (eventSet[type] || []).forEach(item => item(Object.freeze(event)));

/**
 * @function on - 注冊全局事件
 * @param {String} type - 事件類型
 * @param {Function} callback - 事件回調(diào)函數(shù)
 */
export const on = (type, callback) => {
 if (!eventSet[type]) {
  eventSet[type] = [];
 }

 if (!callback instanceof Function) {
  throw new Error('callback must be a Function!');
 }

 return eventSet[type].push(callback)
};

/**
 * @function off - 取消對某事件的監(jiān)聽
 * @param {String} type - 事件類型 
 * @param {Number} id - 需要取消的事件ID,即 registEvent 所返回的值
 */
export const off = (type, id) => {
 if (!eventSet[type]) return

 eventSet[type][id - 1] = EMPTY_HANDLER

 // 如果某類事件已經(jīng)全被取消的話,將其置為空數(shù)組
 const noListener = !eventSet[type].reduce((pre, cur) => (cur && cur === EMPTY_HANDLER) || pre, false);
 if (noListener){
  eventSet[type] = []
 };
}

然后是對 Page 函數(shù)的魔改:

/**
 * @file utils/auth-page.js
 */

import { on } from '/event.js';

export const AuthPage = function(options){
 const { onAuth, data, onLoad } = options;
 const userInfo = {
  nickName: '', // 昵稱
  account: '', // 賬號
  avatar: { // 頭像
   small: '',
   middle: '',
   large: ''
  },
  title: 'student', // 頭銜
  phoneNumber: 0, // 電話號碼
  gender: 'secret', // 性別
  'class': '' // 班級
 }

 if (options.data){
  options.data.authorized = false;
  options.data.userInfo = userInfo
 } else {
  options.data = {
   authorized: false,
   userInfo: userInfo
  }
 }

 /**
  * 仍舊調(diào)用原始的 Page 方法
  */
 Page(Object.assign(
  options,
  {
   onLoad: function () {
    const { authorize, userInfo } = getApp().globalData;

    // 執(zhí)行開發(fā)者期望的 onload 事件
    onLoad instanceof Function && onLoad.bind(this)(arguments);

    // 頁面初始化時,若已經(jīng)授權(quán),直接執(zhí)行授權(quán)回調(diào)
    // 否則將授權(quán)回調(diào)注冊為授權(quán)事件回調(diào)
    if (onAuth instanceof Function){
     if (authorize.authorized){
      onAuth.bind(this)({
       type: 'authorize',
       authorized: true,
       token: authorize.token,
       userInfo: userInfo
      });
     } else {
      on('authorize', onAuth.bind(this));
     }
    }
   }
  }
 ));
}

最后,在登錄組件的里:

import { emit } from '../../utils/event.js';

wx.login({
  success: res => {
    // ...這里省略了一些復雜的登錄流程
    getApp().globalData.authorize = {
      authorized: true
    };
    emit('authorize', res);
  }
})

以上就是怎么在微信小程序中監(jiān)聽用戶登錄事件,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI