
Member-only story
Automatic routing in Vue.js applications
One of the things that I like about the Nuxt framework is its automatic routing capability. You just have to put all you page components into an appropriate folder structure and everything just works; you don’t have to write the rules for vue-router manually.
Recently I started working on a new project based on Vue.js and I wanted to do something similar, but for various reasons I didn’t want to use Nuxt. I found the vue-auto-routing package which was exactly what I was looking for. It’s essentially a small webpack plugin which automatically generates the routing configuration based on the content a given directory. It has similar capabilities and uses the same rules as Nuxt, so it’s very easy to use.
The whole idea behind automatic routing is that the structure of directories in your source code is analogous to the structure of page URLs. Let’s assume that our application has a module for managing users which uses the following URLs:
- /users (list of users)
- /users/add (adding a new user)
- /users/123 (details of a user)
- /users/123/edit (editing an existing user)
This could be represented by the following structure in the source code:
pages
|- users
| |- index.vue
| |- add.vue
| |- _id
| | |- index.vue
| | |- edit.vue
The index.vue, add.vue and edit.vue files are Vue.js components which represent the pages of the application. The underscore in the _id
directory name means that it’s a dynamic parameter.
You no longer have to manually write code such as this:
import Router from 'vue-router';const routes = [
{
path: '/users',
component: () => import( '@/pages/UsersList.vue' )
},
{
path: '/users/add',
component: () => import( '@/pages/UsersAdd.vue' )
},
{
path: '/users/:id',
component: () => import( '@/pages/UsersDetails.vue' )
},
// ... etc. ...
];const router = new Router( { routes } );
The entire routes
array is generated automatically, so you only need to write this:
import Router from 'vue-router';
import routes from 'vue-auto-routing';