踩坑记录!
学习就是要把每个细微的知识点都弄清楚,不然后面要花很多时间去解决
问题:
原代码:
// 处理权限相关信息
import router from "@/router";
import { getToken } from "@/composables/auth";
import { toast } from "./composables/util";
// 全局前置守卫
router.beforeEach((to, from, next) => {
const token = getToken();
// 没有登录,强制跳转到登录页面
if (!token && to.path != "/login") {
toast("请先登录", "error");
next({ path: "/login" });
return;
}
//防止重复登录
if (token && to.path == "/login") {
toast("请无重复登录", "error");
return next({ path: from.path ? from.path : "/" });
}
});
错误解析
在路由中把重定向理解为默认路由
重定向:用户载访问A的时候,强制用户跳转带地址C从而展示特定的组件页面,简而言之就是指定一个新的地址
改正
把在路由里面设置的重定向取消
// 处理权限相关信息
import router from "@/router";
import { getToken } from "@/composables/auth";
import { toast } from "./composables/util";
// 设置哪些页面是属于白名单的
const witheList = ["/login"];
function isWitheRoute(path) {
return witheList.includes(path);
}
// 全局前置守卫
router.beforeEach((to, from, next) => {
const token = getToken();
// 判断如果是白名单就直接放行
if (isWitheRoute(to.path)) {
next();
return;
}
// 没有登录,强制跳转到登录页面
if (!token && to.path != "/login") {
toast("请先登录", "error");
next({ path: "/login" });
return;
}
//防止重复登录
if (token && to.path == "/login") {
toast("请无重复登录", "error");
return next({ path: from.path ? from.path : "/" });
}
next()
});