第一步 我們創建一個攔截的文件 intercept.js
function identityFilter(pageObj) {
if (pageObj.onShow) {
let _onShow = pageObj.onShow;
pageObj.onShow = function () {
wx.getSetting({
success: (res) => {
// 判斷是否登錄以及授權了
if (res.authSetting['scope.userInfo'] && wx.getStorageSync('userinfo')) {//授權了,可以獲取用戶信息了
//獲取頁面實例,防止this劫持
let currentInstance = getPageInstance();
_onShow.call(currentInstance);
} else {
//重定向到指定的頁面
wx.redirectTo({
url: "/pages/authorize/authorize"
});
}
}
})
}
}
return pageObj;
}
function getPageInstance(){ // 獲取去往的頁面
var pages = getCurrentPages(); // getCurrentPages小程序獲取頁面棧函數
return pages[pages.length - 1];
}
exports.identityFilter = identityFilter;
第二步使用路由攔截
// 假設在我的頁面需要使用到路由攔截
let intercept = require('../../../utils/intercept.js')
Page(filter.identityFilter({
/**
* 頁面的初始數據
*/
data: {
},
/**
* 生命週期函數--監聽頁面加載
*/
onLoad: function (options) {
},
/**
* 生命週期函數--監聽頁面初次渲染完成
*/
onReady: function () {
},
/**
* 生命週期函數--監聽頁面顯示
*/
onShow: function () {
},
/**
* 生命週期函數--監聽頁面隱藏
*/
onHide: function () {
},
/**
* 生命週期函數--監聽頁面卸載
*/
onUnload: function () {
},
/**
* 頁面相關事件處理函數--監聽用戶下拉動作
*/
onPullDownRefresh: function () {
},
/**
* 頁面上拉觸底事件的處理函數
*/
onReachBottom: function () {
},
/**
* 用戶點擊右上角分享
*/
onShareAppMessage: function () {
}
})
)