How to set up Vue.js routing

In Vue, routing allows users to navigate between web pages without having to refresh the page, which makes navigation in a web application simple, fast, and pleasant.

Routing is one of the most powerful features of modern single-page web applications (SPA). On the client-side, modern single-page apps, such as a Vue application, can transition from page to page without requesting the server.

Vue.js does not have a built-in router feature. To use vue-router, you can install it via the Vue CLI.

You can install it through npm:

npm  install vue-router

Or you can use the CDN alongside Vue CDN:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

After installing the router, you can use router-link to create a route in your Vue component.

<router-link to = "/route1">Router Link 1</router-link>
<router-link to = "/route2">Router Link 2</router-link>

While you can easily include vue-router with vue-cli, I think it’s worthwhile to know how to install it yourself.

Let’s set up a simple example of vue-router.

Run the command below to add vue-router to our project.

npm install vue-router

Then, in our src/main.js file, we include router inside our Vue instance.

import Vue from 'vue'
import App from './App.vue'
import router from './router'// loads from src/router/index.js
new Vue({
router,
render: h => h(App),
}).$mount('#app')

Create an src/router folder that contains an index.js file with the contents below.

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "home",
component: Home
},
{
path: '/about',
name: 'about',
component: About
}
]
const router = new VueRouter({
mode: 'history',
routes
})
export default router

Now we’ve set up our vue-router, but there’s no way to see it yet.

We can use the router-view element to accomplish this. The router-view element essentially provides a location for vue-router to render whatever component the current URL resolves to.

We’ll put router-view in the App.vue root component for our example. Let’s also create some links so we can swap back and forth between our two paths. vue-router employs special router-link link elements with a to attribute that map to a component.

<template>
<div id="app">
<router-link to='/'>Home</router-link>
<router-link to='/about'>About Us</router-link>
<router-view />
</div>
</template>

When we run our app, we should see our home component rendering. If we click our router-link elements, the content and the URL will change.

Free Resources