Defining routes

To separate out the routes into different files within our application, we can firstly create a file under src/components/user named user.routes.js. Each time we have a different feature set (that requires routes), we can create our own *.routes.js file that can be imported into the router's index.js.

For now, we can just export a new empty array:

export const userRoutes = [];

We can then add the routes to our index.js (even though we have none defined yet):

import { userRoutes } from '../components/user/user.routes';

const routes = [...userRoutes];

We're using the ES2015+ spread operator, which allows us to use each object in the array instead of the array itself.

To then initialize the router, we can then create a new VueRouter and pass along the routes, as follows:

const router = new VueRouter({
// This is ES2015+ shorthand for routes: routes
routes,
});

Finally, let's export the router so that it can be used inside our main Vue instance:

export default router;

Inside main.js, let's import the router and add it to the instance, as shown:

import Vue from 'vue';
import App from './App.vue';
import router from './router';

new Vue({
el: '#app',
router,
render: h => h(App),
});