将路由拆分为单独的文件

时间:2018-01-15 14:27:22

标签: vue.js vuejs2

我正在开发一个相当大的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,路由器/ index.js`?

1 个答案:

答案 0 :(得分:5)

在单独的文件中:

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
]
  

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