路由页面过多,router.js该如何优化?

KenOscar
  • 842

一个前人遗留的老旧项目,最近接手新增项目,发现一个问题,就是router.js过于冗余,新增 router需要添加的东西太多,有没有好的方法可以优化一下

router.js

import Vue from 'vue';
import Router from 'vue-router';

const Layout = r => require.ensure([], () => r(require('@/router/Layout/Layout.vue')), 'Layout');
const Login = r => require.ensure([], () => r(require('@/router/Login/Login.vue')), 'Login');
const error = r => require.ensure([], () => r(require('@/router/404.vue')), '404');
const Index = r => require.ensure([], () => r(require('@/router/index.vue')), '404');

// const WorkPlatform = r => require.ensure([], () => r(require('@/router/WorkPlatform/WorkPlatform.vue')), 'Components');
//合同管理
const Contract = r => require.ensure([], () => r(require('@/router/Contract/Contract.vue')), 'Components');
const Customer = r => require.ensure([], () => r(require('@/router/Contract/Customer.vue')), 'Components');

此处往下开始 省略 80个路由页面加载,随着后期新增功能,估计还会更多
.....

Vue.use(Router);
const router = new Router({
  routes:[
    
    {
      path: '/',
      redirect: '/Index'
    },
    {
      name: '登录',
      path: '/login',
      component: Login,
    },

    {
      path: '/',
      name: '首页',
      component: Layout,
      children: [
        {
          path: '/Index',
          name: 'Index',
          component: Index,
          meta: {
            title: '首页',
            type: 'menu',
            active: false,
            unLogin: true,
            index: "/Index"
          }
        },
        {
          path: '/Contract',
          name: 'Contract',
          component: Contract,
          meta: {
            title: '合同管理',
            type: 'menu',
            active: false,
            unLogin: true,
            index: "/Contract"
          }
        },
        
        .......此处往下开始,省略80个左右的 路由页面配置.........
  ]

})

export default router;

目前路由的引入跟配置都在这一个页面,每次新增路由配置 都要在这里面配置,感觉比较麻烦,而且代码很长,维护比较麻烦,求教有没有更好,更合理的配置

ps. router文件夹下 除了每个页面的路由之外,很多弹窗页面也被写成了.vue放在对应模块的文件夹下

回复
阅读 398
4 个回答

我们现在是通过后台管理路由,再通过授权给用户角色,在登陆时返回用户角色的路由表,然后动态添加到 vue-router 中,但是需要后端配合,改动很大。

也有简单的方式,我在做外包的时候会用,你可以参考一下,其实就是拆分路由文件:

import Vue from "vue";
import VueRouter from "vue-router";
// 拆分开的不同权限的路由js
import contestant from "./contestant";  // 普通用户
import judge from "./judge"; // 裁判用户
import admin from "./admin"; // 管理员用户
import enter from "./enter"; // 登录注册页

Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  linkActiveClass: "active",
  routes: [
    {
      path: "/",
      name: "index",
      redirect: "enter",
      component: () => import("views/layout"),
      children: [contestant, judge],
    },
    admin,
    enter,
    {
      path: "*",
      name: "page404",
      redirect: "/home",
    },
  ],
});
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err);
};
export default router;

然后拆分的单个用户的路由文件:

import store from "@/store";
const judge = {
  path: "/judge",
  name: "judge",
  redirect: () => {
    const status = store.state.user.info.status || -1;
    return status === 3 ? "/judge/assignments" : "/judge/profile";
  },
  component: () => import("views/routerRender"),
  children: [
    {
      path: "/judge/profile",
      name: "judge-profile",
      component: () => import("views/home/judge/profile"),
    },
    {
      path: "/judge/assignments",
      name: "judge-assignments",
      component: () => import("views/home/judge/assignments"),
    },
    {
      path: "/judge/message",
      name: "judge-message",
      component: () => import("views/home/message"),
    },
  ],
  beforeEnter: (to, from, next) => {
    if (
      localStorage.getItem("token") &&
      Number(localStorage.getItem("type")) === 2
    ) {
      next();
    } else {
      localStorage.clear();
      next("/login");
    }
  },
};
export default judge;
已参与了 SegmentFault 思否「问答」打卡,欢迎正在阅读的你也加入。

const Login...

类似这样的不要,改为写到下面

{
  name: '登录',
  path: '/login',
  component: () => import("../pages/Login/Login"),
},

image.png

已参与了 SegmentFault 思否「问答」打卡,欢迎正在阅读的你也加入。

有那么大的业务量,路有多是不可避免的,通常会拆分路由配置文件,比如router/index.js,router/home.js,router/login.js....,根据业务起名。封装减少路由代码量的话,不是不行,得看是不是真的有必要,因为代码量的减少会造成逻辑复杂,可读性会变差,维护成本增加。

模块路由:写在对应的模块里

import { RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/settings',
    name: 'settings',
    component: () => import('./index.vue'),
  },
  {
    path: '/role',
    name: 'role',
    component: () => import('./role/index.vue'),
  },
  {
    path: '/menu',
    name: 'menu',
    component: () => import('./menu'),
  },
  {
    path: '/test',
    name: 'test',
    component: () => import('./test/index.vue'),
  },
]
export default routes

引入到项目路由里:

import { App } from '../model'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import settingsRoutes from '../views/settings/routes'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'index',
    component: () => import('../views/index.vue'),
    children: [
      {
        path: '', // NOTE path 为 '' 否则 路径为 / 时,不会渲染 home 组件
        name: 'home',
        component: () => import('../views/home/index.vue'),
      },
      ...settingsRoutes,
    ],
  },
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})
export const setupRouter = (app: App) => {
  app.use(router)
  return app
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏