route.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { createRouter, createWebHashHistory } from 'vue-router';
  2. import NProgress from 'nprogress'
  3. import NoteLayout from './layouts/NoteLayout.vue'
  4. import store from './store'
  5. const routes = [
  6. {
  7. path: '/',
  8. redirect: '/index',
  9. component: NoteLayout,
  10. children: [
  11. { path: 'index', name: 'index', component: () => import('./pages/index.vue') }
  12. ]
  13. },
  14. {
  15. path: '/login',
  16. name: 'login',
  17. component: () => import('./pages/login/index.vue')
  18. }
  19. ]
  20. const router = createRouter({
  21. // 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
  22. history: createWebHashHistory(),
  23. routes, // `routes: routes` 的缩写
  24. })
  25. router.beforeEach((to, from, next) => {
  26. NProgress.start();
  27. const { user, getUserInfo } = store.getState('user')
  28. if (!user.token) {
  29. NProgress.done();
  30. if (to.name != 'login') {
  31. next({ name: 'login' })
  32. } else {
  33. next()
  34. }
  35. } else {
  36. if (!user.id) {
  37. getUserInfo(user.token).then(() => {
  38. NProgress.done();
  39. next()
  40. })
  41. } else {
  42. NProgress.done();
  43. next()
  44. }
  45. }
  46. })
  47. export default router;