vue-router如何批量设置,上百个页面逐个import太多了

//router.js

import Router from 'vue-router'
import Vue from 'vue'
import login from './components/views/login'
import chat from './components/views/chat'
import App from './index'

Vue.use(Router)

export default new Router({
    mode: 'abstract',
    routes: [
        { path: '/login',component:login},
        { path:'/chat',component:chat},
        { path:'/',component:App}
        ]
})

举个例子,上面只有3个页面,就需要import 3次,下面routes要写3个映射。
如果是上百个页面的系统,不是要写死人?

阅读 11.2k
8 个回答

再一次提到require.context,按照一定结构去放对应文件就可以,可以适当改变路由定义,支持懒加载

 const routes = [
    { path: '*', redirect: '/index' }
  ];
 importPages(require.context('./views', true, /\.vue$/,'lazy'))
 function importPages (r) {
    r.keys().forEach(key => {
      routes.push({ path: (key.split('.'))[1], component: ()=>r(key)})
    });
  }
例如这样
{
  "zh-CN": [
    {
      "name": "login",
      "path": "/login",
      "hidden": true
    },
    {
      "name": "dashboard",
      "path": "",
      "meta": { "title": "dashboard", "icon": "dashboard" },
      "children": [
        { 
          "path": "dashboard/index",  
          "name": "dashboardindex", 
          "meta": { "title": "dashboard", "icon": "dashboard" }
        }
      ]
    },
    {
      "path": "/form",
      "name": "form",
      "meta": {
        "title": "form",
        "icon": "form"
      },
      "children": [
        { 
          "path": "create",  
          "name": "create", 
          "meta": { "title": "createForm","icon": "" }
        },
        { 
          "path": "edit",  
          "name": "edit", 
          "meta": { "title": "editForm", "icon": ""}
        }
      ]
    }
  ]
}
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
import Layout from '../views/layout/Layout'
import navConfig from './nav.config.json'
const LOAD_DOCS_MAP = {
  'zh-CN': (lang, path) => {
    return r => require.ensure([], () =>
      r(require(`../views${lang}/${path}.vue`)),
    'zh-CN');
  }
};

const loadDocs = function(lang, path) {
  return LOAD_DOCS_MAP["zh-CN"](lang, path);
};
const registerRoute = (navConfig) => {
  let route = [];
  navConfig.forEach((lang, index) => {
    let navs = lang.children;
    if(lang.children){
      route.push({
        path: lang.path,
        redirect: `${lang.path}/${lang.children[0].path}`,
        component: Layout,
        meta:lang.meta,
        children: []
      });
      navs.forEach(nav => {
          addRoute(nav, lang, index);
      });
    }else{
      if(lang.hidden){
        route.push({
          path: lang.path,
          component: loadDocs(lang.path,"index"),
          hidden: true,
          meta: {
            title: "",
            icon: ""
          },
        });
      }else{

      }
    }
  });
  function addRoute(page, lang, index) {
    const component = loadDocs(lang.path,page.path);
    let child = {
      path: page.path,
      meta: page.meta,
      name: page.name,
      component: component.default || component
    };

    route[index].children.push(child);
  }

  return route;
};

let route = registerRoute(navConfig["zh-CN"]);




export default new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: route,
})

你可以反过来思考这样的两个问题

  1. 为什么一样要手写Router?
  2. Router的所有功能都是我们需要的吗?

Router是什么,他就像是一本字典,带领你走向应用的站点地图。既然是字典,一一对应不是更好吗?既然能做一一对应,也就不需要手写,仅仅只需要进行一次目录读取即可。你可以使用nodejs进行预读,也可以通过webpack进行预读,按照文件的摆放结构来生成路由。这个能解决第一个问题,至于第二个问题,其实大部分路由的功能我们是用不到的,或者可以封装在你自己的框架中,以减少开发者的编写和维护成本。
你可以参考一下nuxt.js,他里面的路由就是被抽象化了的,你只需要按要求合理的放文件和文件夹即可。

给你高高逼格方案也是我们项目使用的:
// 封装getComponent方法加载所有页面组件, 此方式实现路由懒加载, 强烈推荐
function getComponent(component) {
// '@' is aliased to src
return (resolve) => {

import(`@/${component}.vue`).then((module) => {
  resolve(module)
})

}
}

路由举例
path: 'home',
component: getComponent('views/Home/index/index'),
meta: {
title: '工作台'
}

推荐问题
宣传栏