76 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-04-13 15:54:07 +08:00
import NProgress from "@/config/nprogress";
import pinia from "@/store/index";
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-04-11 13:07:43 +08:00
import { storeToRefs } from "pinia";
import { useUserInfoStore } from "@/store/user-info";
2024-04-13 15:54:07 +08:00
import { useRoutesListStore } from "@/store/route-list";
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(),
/**
2024-04-13 15:54:07 +08:00
* addRoute动态添加
* 1staticRoutes登录页
* 2notFoundAndNoPower 404401 No match found for location with path 'xxx'
2024-03-31 15:51:00 +08:00
* 2 notFoundAndNoPower 404401
2024-04-13 15:54:07 +08:00
* notFoundAndNoPower 404401
* notFoundAndNoPower layout容器展示
2024-03-31 15:51:00 +08:00
*/
2024-04-13 15:54:07 +08:00
routes: [...staticRoutes, ...notFoundAndNoPower]
2024-03-31 15:51:00 +08:00
});
2024-04-13 15:54:07 +08:00
/**
*
* 1token
* 2token
* 3tokenhome页
* 4token
*
* routeTree不能持久化缓存
* 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-13 15:54:07 +08:00
const routeStore = useRoutesListStore(pinia);
const { routeTree } = storeToRefs(routeStore);
// 如果缓存的路由是0则说明未动态添加路由先添加再跳转
// 解决刷新页面404的问题
if (routeTree.value.length == 0) {
await initSetRouter();
next({ path: to.path, query: to.query });
} else {
// 动态路由添加过走这里,直接放行
next();
}
2024-04-08 20:25:28 +08:00
}
2024-03-31 15:51:00 +08:00
});
// 路由跳转错误
router.onError(error => {
NProgress.done();
console.warn("路由错误", error.message);
});
// 路由加载后
router.afterEach(() => {
NProgress.done();
});
export default router;