Splitting routes into separate files

2019-02-26 14:32发布

I am developing a Vue app which is quite big, and I now I have to write all the routes on one page in router/index.js and it is already becoming too long to like or even maintain. The index.js page is full of statements like...

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

Since my app can be grouped into "modules", is there a way to split the routes into separate files (both the import statements and the router entries) in like router/this.js,router/that.js...', then add them to the main route page,router/index.js`?

标签: vue.js vuejs2
1条回答
看我几分像从前
2楼-- · 2019-02-26 14:58

In a seperate file:

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
    },
]

in your route file import the external routes and use the spread operator:

import externalRoutesOne from './externalRoutesOne'
import externalRoutesTwo from './externalRoutesTwo'
var router = new Router({                  
routes: [
  ...externalRoutesOne,
  ...externalRoutesTwo
]
查看更多
登录 后发表回答