76 lines
2.5 KiB
TypeScript
Raw Normal View History

2024-03-31 15:51:00 +08:00
import { createRouter, createWebHashHistory } from "vue-router";
2024-04-12 00:31:21 +08:00
import { staticRoutes, notFoundAndNoPower } from "@/router/route.ts";
2024-04-11 00:15:57 +08:00
import { initSetRouter } from "@/router/route-output";
2024-03-31 15:51:00 +08:00
import NProgress from "@/config/nprogress";
2024-04-11 13:07:43 +08:00
import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { useUserInfoStore } from "@/store/user-info";
2024-03-31 15:51:00 +08:00
/**
* vue的路由示例
* @method createRouter(options: RouterOptions): Router
* @link https://next.router.vuejs.org/zh/api/#createrouter
*/
2024-04-12 00:31:21 +08:00
const router = createRouter({
2024-03-31 15:51:00 +08:00
history: createWebHashHistory(),
/**
*
* 1notFoundAndNoPower 404401 No match found for location with path 'xxx'
* 2 notFoundAndNoPower 404401
* 404401 layout 404401
*/
2024-04-12 00:31:21 +08:00
routes: [...staticRoutes, ...notFoundAndNoPower] // 这里只需要设置兜底路由即可其它的路由通过addRoute动态添加
2024-03-31 15:51:00 +08:00
});
// 路由加载前
router.beforeEach(async (to, from, next) => {
NProgress.start(); // 开启进度条
2024-04-11 13:07:43 +08:00
const store = useUserInfoStore(pinia);
const { token } = storeToRefs(store);
2024-03-31 15:51:00 +08:00
console.log(to, from);
2024-04-11 13:07:43 +08:00
if (to.path === "/login" && !token.value) {
2024-04-08 20:25:28 +08:00
next();
2024-04-11 13:07:43 +08:00
} else if (!token.value) {
2024-04-08 20:25:28 +08:00
next("/login");
2024-04-11 13:07:43 +08:00
} else if (to.path === "/login" && token.value) {
2024-04-08 20:25:28 +08:00
next("/home");
} else {
2024-04-11 00:15:57 +08:00
initSetRouter();
2024-04-10 00:20:31 +08:00
next();
2024-04-08 20:25:28 +08:00
}
2024-03-31 15:51:00 +08:00
// if (to.path === "/login" && !sessionStorage.getItem("token")) {
// next();
// } else if (!sessionStorage.getItem("token")) {
// next("/login");
// } else if (to.path === "/login" && sessionStorage.getItem("token")) {
// next("/home");
// } else {
// // 如果进的不是login则判断路由动态添加
// // 获取缓存的路由store
// const stores = useRoutesListStore(pinia);
// const { routesList } = storeToRefs(stores);
// // 如果缓存的路由是0则说明未动态添加路由先添加再跳转
// // 解决刷新页面404的问题
// if (routesList.value.length == 0) {
// await initSetRouter();
// next({ path: to.path, query: to.query });
// } else {
// // 动态路由添加后走这里,直接放行
// next();
// }
// }
});
// 路由跳转错误
router.onError(error => {
NProgress.done();
console.warn("路由错误", error.message);
});
// 路由加载后
router.afterEach(() => {
NProgress.done();
});
export default router;