• addInterceptor.js
import config from "@/common/config.js";
import tab from "@/common/plugins/tab.js";
import modal from "@/common/plugins/modal.js";
import {
	getToken,
	getLogin
} from "@/common/auth";

export const addRouterInterceptor = () => {
	const whitePages = [
		"/pages/login"
	];
	let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
	list.forEach((item) => {
		uni.addInterceptor(item, {
			invoke(e) {
				// 判断是否是白名单页面
				if (!whitePages.includes(e.url)) {
					// 检查登录状态
					if (!Boolean(getToken()) && getLogin() != 1) {
						const currentPage = getCurrentPages().pop();
						const route = currentPage.route;
						const options = currentPage.options;
						let fullPath = "/" + route;
						if (Object.keys(options).length) {
							const params = Object.keys(options)
								.map((key) => `${key}=${options[key]}`)
								.join("&");
							fullPath += "?" + params;
						}
						console.log("当前路径:", fullPath);
						modal.msgError("请先登录!");
						setTimeout(() => {
							tab.reLaunch(
								`/pages/login?redirect=${encodeURIComponent(fullPath)}`
							);
						}, 500);
						return false;
					}
				}
				return true;
			},
			fail(err) {
				console.log("拦截失败:", err);
			},
		});
	});
};

// 检查 tab 页面访问
const tabPages = ["/pages/work/index", "/pages/mine/index"];
tabPages.forEach((tabPage) => {
	if (!Boolean(getToken()) && getLogin() != 1) {
		if (tabPage != "/pages/login") {
			modal.msgError("请先登录!");
			setTimeout(() => {
				tab.reLaunch("/pages/login");
			}, 500);
		}
	}
});
  • interceptor.js
import { getToken } from "./auth";

// 页面白名单,不受拦截
const whiteList = [
  "/pages/login"
];
function hasPermission(url) {
  let islogin = Boolean(getToken());
  // 在白名单中或有登录判断条件可以直接跳转
  if (whiteList.indexOf(url) !== -1 || islogin) {
    console.log("跳转的页面在白名单内或是已登录");
    return true;
  }
  console.log("跳转的页面不在白名单内且未登录");
  return false;
}
uni.addInterceptor(["navigateTo", "redirectTo", "reLaunch", "switchTab"], {
  invoke(e) {
    if (!hasPermission(e.url)) {
      uni.reLaunch({
        url: "/pages/login",
      });
      return false;
    }
    return true;
  },
  success(e) {},
});

uni.addInterceptor("switchTab", {
  invoke(e) {
    if (!hasPermission(e.url)) {
      uni.reLaunch({
        url: "/pages/login",
      });
      console.log("跳转的页面在白名单内或是已登录");
      return false;
    }
    console.log("跳转的页面不在白名单内且未登录");
    return true;
  },
  success(e) {},
});

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐