zoukankan      html  css  js  c++  java
  • vue之全局守卫

    Vue的路由守卫是什么东西呢?
    第一次接触很懵逼,知道自己遇到了这样一个需求,
    在页面之间进行路由跳转时,需要进行一个判断,如果下一个页面是需要登录后才能进入的页面,那么就需要在点击进入该页面的时候进行守卫的判断,判断用户是否登录,如果登录过了。就直接进入需要进入的页面,如果没有登录过,则进入登录页面。
    那么问题来了,怎么知道登录过还是没有登录过呢?
    在点击登录的时候,会请求后台的api,这时,后台会返回一个token字段。我们需要将该字段存储到storage或者cookie中。然后在路由守卫中加入读取出来判断他是否存在久可以判断是否登录过。
    一般我们选择存入storage中,因为cookie会在每次请求时,伴随发送。性能上没有storage好些。
    下面是一个例子:
    router.js
    import Vue from 'vue';
    import Router from 'vue-router';
    import LoginPage from '@/pages/login';
    import HomePage from '@/pages/home';
    import GoodsListPage from '@/pages/good-list';
    import GoodsDetailPage from '@/pages/good-detail';
    import CartPage from '@/pages/cart';
    import ProfilePage from '@/pages/profile';
     
    Vue.use(Router)
     
    const router = new Router({
      routes: [
        {
          path: '/',  // 默认进入路由
          redirect: '/home'   //重定向
        },
        {
          path: '/login',
          name: 'login',
          component: LoginPage
        },
        {
          path: '/home',
          name: 'home',
          component: HomePage
        },
        {
          path: '/good-list',
          name: 'good-list',
          component: GoodsListPage
        },
        {
          path: '/good-detail',
          name: 'good-detail',
          component: GoodsDetailPage
        },
        {
          path: '/cart',
          name: 'cart',
          component: CartPage
        },
        {
          path: '/profile',
          name: 'profile',
          component: ProfilePage
        },
        {
          path: '*',   // 错误路由
          redirect: '/home'   //重定向
        },
      ]
    });
     
    // 全局路由守卫
    router.beforeEach((to, from, next) => {
      console.log('navigation-guards');
      // to: Route: 即将要进入的目标 路由对象
      // from: Route: 当前导航正要离开的路由
      //如果next为空则路由正常进行跳转,如果next不为空,则进行跳转时,会中断
     
      const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile'];
      let isLogin = global.isLogin;  // 是否登录,一般从storage中读取
      // 未登录状态;当路由到nextRoute指定页时,跳转至login
      if (nextRoute.indexOf(to.name) >= 0) {  
        if (!isLogin) {
          console.log('what fuck');
          router.push({ name: 'login' })
        }
      }
      // 已登录状态;当路由到login时,如果已经登录过,则跳转至home
      if (to.name === 'login') {
        if (isLogin) {
          router.push({ name: 'home' });
        }
      }
      next();
    });
     
    export default router; 
  • 相关阅读:
    前插法创建带头节点的单链表
    利用Oracle数据库发送邮件
    关于如何给C#中的ListBox控件添加双击事件
    类似QQ表情的功能,包括动态绑定图片
    ASP.NET 缓存技术总结
    VS2008 快捷键大全
    Oracle 中union的用法
    C#找到Excel中的所有Sheetname的方法
    推荐一个学习XPath的网站
    Oracle游标使用大全
  • 原文地址:https://www.cnblogs.com/bgwhite/p/9798958.html
Copyright © 2011-2022 走看看