【问题标题】:Splitting routes into separate files将路由拆分为单独的文件
【发布时间】:2018-06-24 04:50:06
【问题描述】:

我正在开发一个非常大的 Vue 应用程序,我现在必须在 router/index.js 的一页上写下所有路由,而且它已经变得太长了,以至于无法喜欢甚至维护。 index.js 页面充满了诸如...之类的语句

import This from '../components/This'
import That from '../components/That'
import ThatOther from '../components/ThatOther'
import ThatOtherOne from '../components/ThatOtherOne'
// and so on and so on...then at the bottom
var router = new Router({                  
routes: [
    {
        path: '/this', 
        name: 'this', 
        component: This
    },
    {
        path: '/that', 
        name: 'that', 
        component: That
    },
// and so on...so many lines of similar and "repetitive" code

由于我的应用程序可以分组为“模块”,有没有办法将路由拆分为单独的文件(import 语句和路由器条目),如router/this.jsrouter/that.js...', then add them to the main route page,router/index.js`?

【问题讨论】:

  • routes 只是一个路由对象数组。您可以根据需要导出任意数量的路由数组并将它们连接在一起,然后再将它们添加到路由器。
  • 谢谢!答案中的例子更好!

标签: vue.js vuejs2


【解决方案1】:

在一个单独的文件中:

import This from '../components/This'
import That from '../components/That'
import ThatOther from '../components/ThatOther'
import ThatOtherOne from '../components/ThatOtherOne'

export default [
  {
        path: '/this', 
        name: 'this', 
        component: This
    },
    {
        path: '/that', 
        name: 'that', 
        component: That
    },
]

在您的路由文件中导入外部路由并使用spread oeprator:

import externalRoutesOne from './externalRoutesOne'
import externalRoutesTwo from './externalRoutesTwo'
var router = new Router({                  
routes: [
  ...externalRoutesOne,
  ...externalRoutesTwo
]

注意:定义路由时需要... 运算符。

【讨论】:

  • 上面看起来没问题,但给出了错误[vue-router] "path" is required in a route configuration。在路由器的routes 属性中,我需要将单独的路由合并到一个数组中还是?
  • 我在使用concat 函数导入它们后合并,然后在routes 属性中使用最终结果。 var routes = This.concat(That) .concat(ThatOther) .concat(ThatOtherOne); var router = new Router({ routes: routes }); 很想知道是否有更“学习”的方式:)
  • 没有必要使用 concat,扩展运算符 (developer.mozilla.org/de/docs/Web/JavaScript/Reference/…) 正是这样做的,如我的示例所示。我目前正在旅途中,但我会在回家后验证我提供的代码以确保它有效。
  • 好吧,好吧,我傻了!我必须承认我忽略了名称开头的...。从没想过这意味着什么。现在我知道得更清楚了。也就是说,您的代码运行良好。太棒了!
  • 注意:定义路由时需要 ... 运算符。
猜你喜欢
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 2011-11-10
  • 1970-01-01
  • 2020-01-12
相关资源
最近更新 更多