在app.js中添加如下两个方法即可:
// 设置需要回调的地址
setCallbackUrl: function(mode) {
return new Promise((resolve,reject) => {
let pages = getCurrentPages(); //获取加载的页面
let currentPage = pages[pages.length - 1]; //获取当前页面的对象
let urlPage = ''; // 存储的跳转地址
let url = currentPage.route; //当前页面url
let argumentsStr = '';
let options = currentPage.options; //如果要获取url中所带的参数可以查看options
for (let key in options) {
let value = options[key];
argumentsStr += key + '=' + value + '&';
}
if(argumentsStr) {
argumentsStr = argumentsStr.substring(0, argumentsStr.length - 1);
urlPage = url + '?' + argumentsStr;
} else {
urlPage = url;
}
let callbackObj = {
callbackUrl: `/${urlPage}`,
mode: mode || 'redirectTo'
}
wx.setStorageSync('callbackObj', JSON.stringify(callbackObj));
resolve();
})
},
// 获取本地可以回调的地址
getCallBackUrl: function() {
return new Promise((resolve,reject) => {
const callbackObj = wx.getStorageSync('callbackObj');
if(callbackObj) {
let resultObj = JSON.parse(callbackObj);
let callbackUrl = resultObj.callbackUrl;
let mode = resultObj.mode;
mode == 'redirectTo' && wx.redirectTo({url: callbackUrl});
mode == 'switchTab' && wx.switchTab({url: callbackUrl});
mode == 'reLaunch' && wx.reLaunch({url: callbackUrl});
mode == 'navigateTo' && wx.navigateTo({url: callbackUrl});
} else {
reject();
}
})
},
跳转到登录页面前通过setCallbackUrl
方法获取即将跳转的当前页面,当登录后调用getCallBackUrl
方法,查看本地是否有需要跳转的地址,没有就在catch
中执行登录后的正常逻辑,比如跳转到我的模块页面。代码如下:
app.getCallBackUrl().catch(() => {
// catch中执行默认的操作
wx.redirectTo({
url: '/pages/my/mycenter/mycenter'
})
})