[Vuejs]-Defining sub routes in components

0👍

It can easily be done. Although it could be discussed whether it should be done or not – it does not really change anything, except possibly reducing the verbosity of the main router file. (In any case, the router definition must have all routes in it, so the difference is merely on the aesthetic side)

Routes are simply Javascript objects – why not doing it like below

In index.vue

const productRoutes = [
  {
    name: 'view',
    path: 'view',
    component: productView
  }, 
  {
    name: 'add',
    path: 'add',
    component: productAdd
  }, 
  {
    name: 'edit',
    path: 'edit',
    component: productEdit
  }, 
]

in the router file

const routes = [
  {
    name: 'products',
    path: '/products',
    component: products,
    children: productRoutes
  }
]

const myRouter = new VueRouter({    
   routes
})

You need to of course add the appropriate import statements – you’ll need
these anyway as the router always needs a reference to the components listed.

Components will then simply be defined by their option object, shown as productAdd, productView, productEdit above.

Leave a comment