Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Vue Router Patterns Chapter 20

$ cd vue-spa

# Install dependencies
$ npm install

# Install Vue Router and Axios
$ npm install vue-router axios

# Run application
$ npm run dev

Enabling the router


We can start off by enabling the VueRouter plugin within our application. To do this, we


can create a new file inside src/router named index.js. We'll use this file to contain all


the router-specific configuration, but we'll separate out each route into different files


depending on the underlying feature.


Let's import and add the router plugin:


import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter)

Defining routes


To separate out the routes into different files within our application, we can first 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.

Free download pdf