小程序页面跳转拦截器(用于未登录,然后点击其他页面跳转登录)
新建Interceptor.js,写入以下代码
let config = {
//不需要登录的页面,白名单
whiteList: [
// "/pages/mine/mine",
"/pages/mine/mine"
],
//登录页
loginPage: "/pages/mine/mine"
}
export default function initApp() {
/**
* 页面跳转拦截器
*/
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
list.forEach(item => { //用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
uni.addInterceptor(item, {
invoke(e) { // 调用前拦截
//获取用户的token
const userInfo = uni.getStorageSync('token'),
//获取要跳转的页面路径(url去掉"?"和"?"后的参数)
url = e.url.split('?')[0];
let notNeed = config.whiteList.includes(url)
// console.log('notNeed',notNeed);
// 如果在whiteList里面就不需要登录
if (notNeed) {
return e
} else {
//需要登录
if (!userInfo) {
uni.switchTab({
url: config.loginPage
})
uni.showToast({
icon:"none",
title:'请先登录'
})
return false
} else {
return e
}
}
},
fail(err) { // 失败回调拦截
console.log('111111',err);
}
})
})
}
APP.vue引入该文件,并放入onLaunch执行