1. 程式人生 > 程式設計 >vue 實現動態路由的方法

vue 實現動態路由的方法

很多時候我們在專案的路由都是在前端配置好的
但是有的時候為了進行全面的許可權控制,會需要後臺給出路由表,前端再渲染。不用在前端配置。

下面主要講一下思路

1、和後臺小哥哥溝通好資料,把我們前端配置的路由表資料給他,他就能看懂了

2、拿到資料需要我們自己再處理

路由中的component後臺是給不了的,這裡我們只需要後臺小哥哥按照我們提供的前端component路徑給資料,我們迴圈載入就可以了

//view就是後臺給的資料
return () => import(`@/view/modules/${view}`);

這樣我們就拿到了最重要的資料,即component。

3、把後臺提供的資料處理成我們需要的路由表

4、新增到路由中

Router.addRoutes(路由資料)

以下講一下我在專案中實現過程

1、新建一個router.js

裡面做些基本的路由操作,比如匯入包,因為我們拿到資料之後還是要自己手動去放到路由中去的
也會寫一寫不需要後臺提供的選單資料,比如我們測試頁面或者login等等

import Vue from "vue";
import Router from "vue-router";
import AppMain from "@/view/modules/main/index";
Vue.use(Router);
export const _CONSTANTS_ROUTERS =
[
  {
    path: "/login",component: () => import("@/view/modules/login/index"),hidden: true
  },{
    path: "",component: AppMain,redirect: "/dashboard",children: [
      {
        path: "/dashboard",component: () => import("@/view/modules/dashboard/index"),name: "Dashboard",meta: { title: "首頁",icon: "dashboard",noCache: true }
      }
    ]
  }
];
export default new Router({
  mode: "history",// 解決vue框架頁面跳轉有白色不可追蹤色塊的bug
  scrollBehavior: () => ({ x: 0,y: 0 }),// scrollBehavior: () => ({ y: 0 }),routes: _CONSTANTS_ROUTERS
});

基本路由表已經建立好了

2、我們在什麼時候進行獲取完整的路由表資料

這個時候我們就要想到路由鉤子函式,當然是Router.beforeEach中做

Router.beforeEach((to,from,next) =>
{
  NProgress.start();
  if (!Token.isEmpty())
  {
    if (to.path === "/login")
    {
      next({ path: "/" });
      NProgress.done();
    }
    else if (to.path === "/404")
    {
      next();
      NProgress.done();
    }
    else
    {
      // 判斷當前使用者是否已拉取完角色資訊
      if (Store.getters.roles.length === 0)
      {
         //拉取路由資料
ACLRepo.listMenuTreeOfCurrentUser().then(response =>
          {
            Store.dispatch("generateRoutes",response).then(() =>
            {
              // 根據roles許可權生成可訪問的路由表
              Router.addRoutes(Store.getters.addRouters); // 動態新增可訪問路由表
              next({ ...to,replace: true }); // hack方法 確保addRoutes已完成,set the replace: true so the navigation will not leave a history record
            });
          });
      }
      else
      {
         next();
      }
    }
  }
  else
  {
    next();
  }
});

3、路由資料重新封裝

generateRoutes

import { _CONSTANTS_ROUTERS } from "@/scripts/router";
import AppMain from "@/view/modules/main/index";
const _PERMISSION = {
  state: {
    routers: _CONSTANTS_ROUTERS,addRouters: []
  },mutations: {
    setRouters: (state,routers) =>
    {
      state.addRouters = routers;
      //和已經存在的路由表拼接
      state.routers = _CONSTANTS_ROUTERS.concat(routers);
    }
  },actions: {
    generateRoutes({ commit },response)
    {
      let asyncRouters = filterAsyncRouter(response);
      asyncRouters.push({ path: "*",redirect: "/404",hidden: true });
      commit("setRouters",asyncRouters);
    }
  }
};
 
function filterAsyncRouter(routers)
{
  // 遍歷後臺傳來的路由字串,轉換為元件物件
  let accessedRouters = routers.filter(router =>
  {
    if (router.meta)
    {
      // 預設圖示處理
      router.meta.icon = router.meta.icon ? router.meta.icon : "component";
    }
    if (router.component === "main")
    {
      // Main元件特殊處理
      router.component = AppMain;
    }
    else
    {
      //處理元件---重點
      router.component = loadView(router.component);
    }
    //存在子集
    if (router.children && router.children.length)
    {
      router.children = filterAsyncRouter(router.children);
    }
    return true;
  });
  return accessedRouters;
}
function loadView(view)
{
  // 路由懶載入
  return () => import(`@/view/modules/${view}`);
}
export default _PERMISSION;

到這裡其實就完成了,理清楚思路,其實很簡單

以上就是vue 實現動態路由的方法的詳細內容,更多關於vue 實現動態路由的資料請關注我們其它相關文章!