guard.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { addTaskbar } from '@/sheep/hooks/useTaskbar';
  2. import $store from '@/sheep/store';
  3. export function setupRouterGuard(router) {
  4. router.beforeEach((to, from, next) => {
  5. let nextPath = '';
  6. const appStore = $store('app');
  7. const isLogin = $store('account').isLogin;
  8. const taskbar = appStore.taskbar;
  9. // 强制登录
  10. if (!isLogin && to.meta.login !== false && to.path !== '/login') {
  11. nextPath = '/login';
  12. }
  13. // 进入首页
  14. if (isLogin && to.path === '/') {
  15. // 默认进入个人页
  16. nextPath = '/admin/profile';
  17. // 查找历史记录
  18. if (taskbar.history.length > 0 && taskbar.list.length > 0) {
  19. let key = taskbar.list.findIndex((page) => page.name === taskbar.history[0]);
  20. if (key !== -1) {
  21. nextPath = taskbar.list[key].path || '/admin/profile';
  22. }
  23. }
  24. }
  25. if (nextPath === '') {
  26. next();
  27. } else {
  28. next(nextPath);
  29. }
  30. });
  31. router.afterEach(async (to, from) => {
  32. // 设置标题
  33. document.title = `${$store('app').info.name}-${to.meta.title}`;
  34. // 添加任务栏历史
  35. if (to.meta.taskbar !== false) {
  36. addTaskbar({
  37. title: to.meta.title,
  38. name: to.name,
  39. path: to.path,
  40. query: to.query,
  41. icon: to.meta.icon,
  42. });
  43. }
  44. });
  45. }