Vue js在不同的文件中分开路由

时间:2017-07-28 09:44:14

标签: javascript vuejs2 vue-router

我正在创建一个单页应用程序,我想将路径文件分成不同的文件

Thta在我的主路由文件index.js中有

export default new Router({
 routes: [
   { path: '/', component: Hello },
   {path :'/users', component: UsersContainerComponent,
       children:[
           {path :'', component: UsersComponent},
           {path :'/create', component: UsersCreateComponent},
           {path :'/update', component: UsersUpdateComponent},

         ]
      },

] })

现在我还有其他功能,不仅包括用户,因此代码变得庞大,我如何将用户路由功能外包到另一个文件中,并且只包含对主路径文件的引用

那么我怎样才能实现这样的目标

export default new Router({
  routes:[
    {path:'users', .....}// here load users routing in another file

    ]
  })

因为这会使代码更具可读性和可管理性。

2 个答案:

答案 0 :(得分:4)

我喜欢disjfa解决方案: Let’s route a vue app 组件路线

import People from '../views/People';
import Welcome from './../views/Welcome';
import Details from './../views/Details';
import Create from './../views/Create';

export default [
  {
    path: '/people',
    name: 'people',
    component: People,
    title: 'People',
    redirect: { name: 'people-welcome' },
    children: [
      {
        path: 'welcome',
        name: 'people-welcome',
        component: Welcome,
      },
      {
        path: 'create',
        name: 'people-create',
        component: Create,
      },
      {
        path: ':id',
        name: 'people-details',
        component: Details,
      },
    ],
  },
];

主要路线

import Vue from 'vue';
import Router from 'vue-router';
import Dashboard from '@/views/Dashboard';
import peopleRoutes from '@/modules/people/router';

Vue.use(Router);

const baseRoutes = [
   ...
];

const routes = baseRoutes.concat(peopleRoutes);
export default new Router({
  routes,
});

答案 1 :(得分:3)

您可以将子项添加到主路径文件中的路径。

{
  path: '/events',
  component: eventspage,
  children: eventroutes,
},

在子路线组件中,您可以执行以下操作:

const eventroutes = [
  {
    path: '',
    name: 'eventlist',
    component: eventlist,
  },
  {
    path: 'info/:id',
    name: 'eventlist',
    component: eventlist,
  },
];

export default eventroutes;

基本上,您可以直接取出子部件内的路径,并将它们作为单独的文件。