vue --》動態路由的實現 (根據用戶的權限來訪問對應的模塊)


  為了設置用戶的訪問權限,所以在一個vue工程中,往往需要前端和后端開發人員共同配合設置動態路由,

進而實現根據用戶的權限來訪問對應的模塊

  1.首先在登錄頁面,前端跟據后端返回的路由信息進行配置,配置后存儲到本地以便使用

login.vue頁面
    在methods中:
  //配置路由的方法 getMenuList(){
       let menuList = '后端給你返回的數據'     let sysRouter
= []; let tempOne = {}; menuList.filter((menuOne, indexOne) => { tempOne = {}; tempOne.title = menuOne.name; //這幾個屬性均為路由的一些配置項以及所用到的一些信息,根據實際情況進行編寫 tempOne.icon = menuOne.icon; tempOne.path = menuOne.perm; tempOne.redirect = menuOne.url; tempOne.children = []; tempOne.component = Main; //Main是個文件 每個頁面都依賴於這個文件 let tempTwo = {}; if (menuOne.children.length > 0) { menuOne.children.filter((menuTwo, indexTwo) => {    tempTwo = {}; tempTwo.title = menuTwo.name; tempTwo.path = menuTwo.url; tempTwo.component = () => import(`@/pages${menuTwo.path}.vue`); tempOne.children.push(tempTwo); }); } sysRouter.push(tempOne); });
        sessionStorage.setItem("sysRouter", JSON.stringify(sysRouter));
    },
  //點擊登錄按鈕的方法
  submitBtn(){
    
let parm = {
                username: this.key,
                password: this.pwd,
             
            };
    api.login(parm).then(res => {
       if(res){
         //首先將你的所需要的信息存儲到本地,例如token,用戶信息的等
         //調用配置路由信息的方法
         //然后跳轉到首頁
         //最后刷新一下頁面,不然會白屏

sessionStorage.setItem("loginToken", res.data.data.token);

          this.getMenuList();
           this.$router.push({
                       path: "/home/home"
                  });
 
           setTimeout(()=>{
                       window.location.reload();
                  },50)

       }
    })
 
         

   }

接下來就是最關鍵的一步 配置 router里面的index.js文件

import Vue from 'vue';
import Router from 'vue-router';
import store from '../store';
import Main from '@/pages/Main.vue';

Vue.use(Router);


/*
 * 
 *  路由重復點擊 警告問題解決
 *  
*/ 
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}



/*
 *---- 登錄前不運行,刷新時運行,用addRoutes加載路由 begin ----
 */
let systemRouter = [];
let localRouter = window.sessionStorage.getItem('sysRouter'); //用於刷新時加載導航 功能和addRoutes等同1
if (localRouter) {
  //因為未登錄 localRouter不存在,故不運行;只有刷新時才運行
  let localJsonRouter = JSON.parse(localRouter);
  systemRouter = localJsonRouter;
  systemRouter.filter(item => {
    //需要重新綁定 component
    item.component = Main;
    if (item.children.length > 0) {
      item.children.filter(itemTwo => {
        itemTwo.component = () => import(`@/pages${itemTwo.path}.vue`);
      });
    }
  });
} else {
  systemRouter = [];
}
/*
 *---- 登錄前不運行,刷新時運行,用addRoutes加載路由 end ----
 */

// 定義其他路由 這一般都為3級路由
let otherRouter = [
  {
    path: '/menu2_0_1',
    title: '設計數據管理',
    icon: 'el-icon-s-opportunity',
    redirect: '/designDataManage/clientRequireManage',
    component: Main,
    children: [
      {
        path: '/designDataManage/clientRequireManage/requireFileList',
        title: '客戶需求管理',
        component: () =>
          import(
            '@/pages/designDataManage/requireFileList/requireFileList.vue'
          )
      },
      {
        path: '/designDataManage/designDataManageHome/designDataList',
        title: '設計數據管理',
        component: () =>
          import(
            '@/pages/designDataManage/designDataList/designDataList.vue'
          )
      },
      {
        path: '/designDataManage/designDataManageHome/FLDataList',
        title: '設計數據管理',
        component: () =>
          import('@/pages/designDataManage/FLfileList/FLfileList.vue')
      },
      {
        path:
          '/designDataManage/designDataManageHome/workAfterFileList',
        title: '設計數據管理',
        component: () =>
          import(
            '@/pages/designDataManage/workAfterFileList/workAfterFileList.vue'
          )
      },
      {
        path: '/designDataManage/designDataManageHome/numFileList',
        title: '設計數據管理',
        component: () =>
          import(
            '@/pages/designDataManage/numFileList/numFileList.vue'
          )
      },
      {
        path: '/designDataManage/printFileManage/printFileList',
        title: '制版文件管理',
        component: () =>
          import(
            '@/pages/designDataManage/printFileList/printFileList.vue'
          )
      }
    ]
  },
  {
    path: '/menu3_0_1',
    title: '工藝數據管理',
    icon: 'el-icon-s-open',
    redirect: '/workDataMange/workDataMangeRepair',
    component: Main,
    children: [
      {
        path: '/workDataMange/workDataMangeRepair/workDataMangeList',
        title: '客戶需求管理',
        component: () =>
          import(
            '@/pages/workDataMange/workDataManageList/workDataManageList.vue'
          )
      }
    ]
  },
  {
    path: '/menu4_0_1',
    title: '打樣任務管理',
    icon: 'el-icon-s-order',
    redirect: '/printTaskManage/printTaskManageHome',
    component: Main,
    children: [
      {
        path:
          '/printTaskManage/printTaskManageHome/printTaskManageList',
        title: '編輯打樣任務',
        component: () =>
          import(
            '@/pages/printTaskManage/printTaskManageList/printTaskManageList.vue'
          )
      }
    ]
  },
  {
    path: '/menu4_0_2',
    title: '打樣任務管理',
    icon: 'el-icon-s-order',
    redirect: '/printOAManage/printOAManageHome',
    component: Main,
    children: [
      {
        path: '/printOAManage/printOAManageHome/prinOAkManageList',
        title: '編輯打樣任務',
        component: () =>
          import(
            '@/pages/printTaskManage/printOAmanageList/printOAmanageList.vue'
          )
      },
      {
        path:
          '/printOAManage/printOAManageHome/prinOAkManageStartWorkList',
        title: '開工',
        component: () =>
          import(
            '@/pages/printTaskManage/prinOAkManageStartWorkList/prinOAkManageStartWorkList.vue'
          )
      },
      {
        path: '/printOAManage/printOAManageHome/paraDetail',
        name: 'paramaDetail',
        title: '工藝參數詳情',
        component: () =>
          import(
            '@/pages/printTaskManage/prinOAkManageStartWorkList/paramaDetail.vue'
          )
      }
    ]
  },
  {
    path: '/menu5_0_2',
    title: '打樣基線管理',
    icon: 'el-icon-s-order',
    redirect: '/printBasicLineManage/importantColorData',
    component: Main,
    children: [
      {
        path:
          '/printBasicLineManage/importantColorData/importantColorDataList',
        title: '關鍵顏色詳情',
        component: () =>
          import(
            '@/pages/printBasicLineManage/importantColorDataList/importantColorDataList.vue'
          )
      }
    ]
  }
];

//聲明路由對象,實例化VueRouter
const router = new Router({
  routes: [
    //登錄路由
    {
      path: '/',
      name: 'login',
      component: () => import('@/pages/login.vue')
    },
    {
      path: '/error',
      name: 'error',
      component: () => import('@/pages/error.vue')
    },
    {
      path: '/resetPassword',
      name: 'resetPassword',
      component: () => import('@/pages/checkPassword/resetPassword.vue')
    },
    {
      path: '/checkNameAndEmail',
      name: 'checkNameAndEmail',
      component: () => import('@/pages/checkPassword/checkNameAndEmail.vue')
    },
    ...systemRouter,
    ...otherRouter
  ]
});

/* * 加載頁面之前 鈎子函數
 
   * 使用場景:一般用在跳轉前需要做校驗的地方
   * to:Route即將要進入的目標 路由對象;
   * from:Route當前導航正要離開的路由;
   * next:Function一定要調用該方法來resolve這個鈎子。執行效果依賴next方法的調用參數。
   * 
*/
router.beforeEach(function (to, from, next) {
  store.dispatch('updateActItem', to.path);

  /*--- 動態綁定路由格式 begin ---*/
  let systemRouter = [];
  let localRouter = window.sessionStorage.getItem('sysRouter'); //用於刷新時加載導航
  //beforeEach,一步小心就進入到了他的死循環,瀏覽器都會崩虧,需要在一開始就加判斷,拿到路由了,就直接next(),
  if (localRouter) {
    let localJsonRouter = JSON.parse(localRouter);
    systemRouter = localJsonRouter;
    systemRouter.filter(item => {
      //需要重新綁定 component
      item.component = Main;
      if (item.children.length > 0) {
        item.children.filter(itemTwo => {
          itemTwo.component = () =>
            import(`@/pages${itemTwo.path}.vue`);
        });
      }
    });
  } else {
    systemRouter = [];
  }
  if (window.sessionStorage.getItem('sysRouter') == null) {
    //不加這個判斷,路由會陷入死循環 !!!!
    router.addRoutes(systemRouter); //動態加載路由
  }



  store.dispatch('updateMenuList', systemRouter);
  next();
  /*--- 動態綁定路由格式 end ---*/
});
export default router;

 

  


免責聲明!

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



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