vue之全局守卫

Vue 的路由守卫是什么东西呢?
第一次接触很懵逼,知道自己遇到了这样一个需求,
在页面之间进行路由跳转时,需要进行一个判断,如果下一个页面是需要登录后才能进入的页面,那么就需要在点击进入该页面的时候进行守卫的判断,判断用户是否登录,如果登录过了。就直接进入需要进入的页面,如果没有登录过,则进入登录页面。
那么问题来了,怎么知道登录过还是没有登录过呢?
在点击登录的时候,会请求后台的 api,这时,后台会返回一个 token 字段。我们需要将该字段存储到 storage 或者 cookie 中。然后在路由守卫中加入读取出来判断他是否存在久可以判断是否登录过。
一般我们选择存入 storage 中,因为 cookie 会在每次请求时,伴随发送。性能上没有 storage 好些。
下面是一个例子:
router.js
  1. import Vue from 'vue';
  2. import Router from 'vue-router';
  3. import LoginPage from '@/pages/login';
  4. import HomePage from '@/pages/home';
  5. import GoodsListPage from '@/pages/good-list';
  6. import GoodsDetailPage from '@/pages/good-detail';
  7. import CartPage from '@/pages/cart';
  8. import ProfilePage from '@/pages/profile';
  9. Vue.use(Router)
  10. const router = new Router({
  11. routes: [
  12. {
  13. path: '/', // 默认进入路由
  14. redirect: '/home' //重定向
  15. },
  16. {
  17. path: '/login',
  18. name: 'login',
  19. component: LoginPage
  20. },
  21. {
  22. path: '/home',
  23. name: 'home',
  24. component: HomePage
  25. },
  26. {
  27. path: '/good-list',
  28. name: 'good-list',
  29. component: GoodsListPage
  30. },
  31. {
  32. path: '/good-detail',
  33. name: 'good-detail',
  34. component: GoodsDetailPage
  35. },
  36. {
  37. path: '/cart',
  38. name: 'cart',
  39. component: CartPage
  40. },
  41. {
  42. path: '/profile',
  43. name: 'profile',
  44. component: ProfilePage
  45. },
  46. {
  47. path: '*', // 错误路由
  48. redirect: '/home' //重定向
  49. },
  50. ]
  51. });
  52. // 全局路由守卫
  53. router.beforeEach((to, from, next) => {
  54. console.log('navigation-guards');
  55. // to: Route: 即将要进入的目标 路由对象
  56. // from: Route: 当前导航正要离开的路由
  57. //如果 next 为空则路由正常进行跳转,如果 next 不为空,则进行跳转时,会中断
  58. const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile'];
  59. let isLogin = global.isLogin; // 是否登录,一般从 storage 中读取
  60. // 未登录状态;当路由到 nextRoute 指定页时,跳转至 login
  61. if (nextRoute.indexOf(to.name) >= 0) {
  62. if (!isLogin) {
  63. console.log('what fuck');
  64. router.push({ name: 'login' })
  65. }
  66. }
  67. // 已登录状态;当路由到 login 时,如果已经登录过,则跳转至 home
  68. if (to.name === 'login') {
  69. if (isLogin) {
  70. router.push({ name: 'home' });
  71. }
  72. }
  73. next();
  74. });
  75. export default router;