jiuyiUniapp/jiuyi/routeIntercept.js

87 lines
2.9 KiB
JavaScript

// 需要登录黑名单
const LoiginWhiteList = [
'pages/mine'
];
// 商家端 黑名单 只要是merchant下面的都是商家端都需要 登录以及商家身份
const shopWhiteList = [
'/pages/merchant'
];
// 标志位,防止无限递归
let isRedirecting = false;
function hasPermission(url) {
let value = {
is: false,
name: 'needLogin'
}; //未通过
// 判断是否需要登录
let needLogin = LoiginWhiteList.includes(url);
// 是否需要商家身份
// 判断shopWhiteList是否存在URL
let needShop = shopWhiteList.includes(url);
if (needShop) {
value.name = 'needShop'
value.is = uni.$store.state.userInfo?.isShop != 1 ? true : false;
}
if (needLogin) {
value.name = 'needLogin'
value.is = uni.$store.state.userInfo?.token ? true : false
}
return value
}
function addInterceptors() {
const methods = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
methods.forEach(method => {
uni.addInterceptor(method, {
invoke(e) {
if (isRedirecting) {
return true; // 防止递归
}
let is = hasPermission(e.url);
if (is.is) {
isRedirecting = true;
switch (is.name) {
case 'needLogin':
uni.showToast({
title: '请先登录',
icon: 'none'
});
uni.reLaunch({
url: '/pages/login/loginPhone'
}).finally(() => {
isRedirecting = false; // 重置标志位
});
break;
case 'needShop':
uni.showToast({
title: '请先入驻',
icon: 'none'
});
uni.reLaunch({
url: '/pages/shop/settle'
}).finally(() => {
isRedirecting = false; // 重置标志位
});
break;
default:
isRedirecting = false; // 重置标志位
break;
}
return false;
}
return true;
},
fail(e) {
console.error(`Interceptor failed for ${method}:`, e);
},
returnValue(e) {
// console.log(`Return value for ${method}:`, e);
},
complete(e) {
// console.log(`Complete for ${method}:`, e);
}
});
});
}
addInterceptors();