vue路由守衛 - 全局 【router.beforeEach((to, from, next】


vue路由守衛 - 全局(router.beforeEach((to, from, next) =>來判斷登錄和路由跳轉狀態)

vue中用路由守衛來做是否登陸判斷,此處我以后台管理項目為例,如下圖:

 主要方法:

  • to:進入到哪個路由去
  • from:從哪個路由離開
  • next:路由的控制參數,常用的有next(true)和next(false)

首先判斷進入的是否是login頁面?然后再判斷是否已經登陸?
已經登陸了就進入你要跳轉的頁面,沒登錄就進入login頁面

為了更加明顯一點,我將頁面命名的簡單一些,ps:
    • Login.vue是登陸頁面
    • Index.vue是全局頁面(包含公共導航組件)
      A.vue是普通頁面(此處我做為首頁)
      B.vue是普通頁面
    • 404.vue是走丟了的404頁面
      //router.js
      import Vue from 'vue'
      import Router from 'vue-router'
      
      Vue.use(Router);
      
      const children = [
        {
          path: 'a',
          name: 'a',
          component: () => import('./views/A.vue'),
          meta: {
            title: 'a頁面',
            keepAlive: false // 無緩存
          }
        },
        {
          path: 'b',
          name: 'b',
          component: () => import('./views/B.vue'),
          meta: {
            title: 'b頁面',
            keepAlive: true // 有緩存
          }
        },
        {
          path: '404',
          name: '404',
          component: () => import('./components/404.vue')
        }
      ];
      const router =  new Router({
        mode: 'history',
        base: process.env.BASE_URL,
        routes: [
          { path: '/', redirect: '/a' },
          { path: '*', redirect: '/404' },
          {
            path: '/login',
            name: 'login',
            component: () => import('./components/Login.vue')
          },
          {
            path: '/',
            component: () => import('./components/Index.vue'), //index是上圖左邊的公共菜單
            children  //此處是站內頁面,頁面在右側container里展示
          }
        ]
      });
      router.beforeEach((to, from, next) => {
        const isLogin = sessionStorage.getItem('isLogin'); //獲取本地存儲的登陸信息
        if (to.name == 'login') { //判斷是否進入的login頁
          if (isLogin == "true") {  //判斷是否登陸
            next({ name: 'a'});  //已登錄,跳轉首頁(a頁面)
          } else {
            next();  //沒登錄,繼續進入login頁
          }
        } else { //如果進入的非login頁
          if (isLogin == "true") {   //同樣判斷是否登陸
            next();  //已登錄,正常進入
          } else {
            next({ name: 'login'});  //沒登錄,跳轉到login頁
          }
        }
      });
      export default router;
      代碼實現

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM