分裂路线为独立的文件

问题描述 投票:3回答:1

我正在开发一个应用程序的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`?

vue.js vuejs2
1个回答
6
投票

在一个单独的文件:

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
]

注意:将它们定义路由时的...操作是必需的。

© www.soinside.com 2019 - 2024. All rights reserved.