refactor(main.ts): ♻️ 抽离一些功能为vue插件
This commit is contained in:
7
src/plugins/i18n.ts
Normal file
7
src/plugins/i18n.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
// 国际化
|
||||
import i18n from "@/lang/index";
|
||||
import type { App } from "vue";
|
||||
|
||||
export function setupI18n(app: App<Element>) {
|
||||
app.use(i18n);
|
||||
}
|
||||
9
src/plugins/icons.ts
Normal file
9
src/plugins/icons.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { App } from "vue";
|
||||
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
|
||||
|
||||
// 注册所有图标
|
||||
export function setupElIcons(app: App<Element>) {
|
||||
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.component(key, component);
|
||||
}
|
||||
}
|
||||
3
src/plugins/index.ts
Normal file
3
src/plugins/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from "./icons";
|
||||
export * from "./i18n";
|
||||
export * from "./permission";
|
||||
60
src/plugins/permission.ts
Normal file
60
src/plugins/permission.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import router from "@/router";
|
||||
import { useUserStore } from "@/store/modules/user";
|
||||
import { usePermissionStore } from "@/store/modules/permission";
|
||||
import NProgress from "@/utils/nprogress";
|
||||
|
||||
export function setupPermission() {
|
||||
// 白名单路由
|
||||
const whiteList = ["/login"];
|
||||
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
NProgress.start();
|
||||
const hasToken = localStorage.getItem("token");
|
||||
if (hasToken) {
|
||||
if (to.path === "/login") {
|
||||
// 如果已登录,跳转首页
|
||||
next({ path: "/" });
|
||||
NProgress.done();
|
||||
} else {
|
||||
const userStore = useUserStore();
|
||||
const hasRoles =
|
||||
userStore.user.roles && userStore.user.roles.length > 0;
|
||||
if (hasRoles) {
|
||||
// 未匹配到任何路由,跳转404
|
||||
if (to.matched.length === 0) {
|
||||
from.name ? next({ name: from.name }) : next("/404");
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
} else {
|
||||
const permissionStore = usePermissionStore();
|
||||
try {
|
||||
const { roles } = await userStore.getUserInfo();
|
||||
const accessRoutes = await permissionStore.generateRoutes(roles);
|
||||
accessRoutes.forEach((route) => {
|
||||
router.addRoute(route);
|
||||
});
|
||||
next({ ...to, replace: true });
|
||||
} catch (error) {
|
||||
// 移除 token 并跳转登录页
|
||||
await userStore.resetToken();
|
||||
next(`/login?redirect=${to.path}`);
|
||||
NProgress.done();
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 未登录可以访问白名单页面
|
||||
if (whiteList.indexOf(to.path) !== -1) {
|
||||
next();
|
||||
} else {
|
||||
next(`/login?redirect=${to.path}`);
|
||||
NProgress.done();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
router.afterEach(() => {
|
||||
NProgress.done();
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user