← Back to all tutorials

Setting up Routing

Install and configure Vue Router — create a single-page application with multiple views and URL-based navigation.

Setting up Routing

Most applications have multiple pages. Vue Router lets you map URLs to components, creating a single-page application (SPA) where navigation happens without full page reloads.

Installing Vue Router

npm install vue-router

Setting Up Routes

// src/router.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from './components/Home.vue';
import AddBlog from './components/AddBlog.vue';

Vue.use(Router);

export default new Router({
    routes: [
        { path: '/', component: Home },
        { path: '/add', component: AddBlog },
    ]
});

Using the Router in main.js

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

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

The router-view Component

<!-- App.vue -->
<template>
    <div id="app">
        <app-header></app-header>
        <router-view></router-view>
    </div>
</template>

<router-view> renders the component that matches the current URL. When the URL changes, a different component is displayed — without a page reload.

How Routing Works

URLComponent Rendered
/Home.vue
/addAddBlog.vue

Key Takeaways

  • vue-router maps URL paths to Vue components
  • <router-view> renders the matched component — it is a placeholder that swaps content
  • Routes are defined as an array of objects with path and component
  • Pass the router to the Vue instance so all components can access routing features