Setting Up and Configuring Vue Router for Single Page Applications

Environment Setup

The first step in implementing client-side routing is installing the Vue Router package. Execute the following comand in your terminal within the project root:

npm install vue-router

Defining View Components

Before configuring the router, prepare the components that will serve as the different views of your application. For example, create Dashboard.vue and Settings.vue.

<!-- Dashboard.vue -->
<template>
  <div class="view-container">
    <h1>System Dashboard</h1>
    <p>Overview of application metrics.</p>
  </div>
</template>

<script>
export default {
  name: 'Dashboard'
}
</script>
<!-- Settings.vue -->
<template>
  <div class="view-container">
    <h1>User Settings</h1>
    <p>Manage your account preferences here.</p>
  </div>
</template>

<script>
export default {
  name: 'Settings'
}
</script>

Router Configuration and Rules

Create a dedicated router configuration file, typically located at src/router/index.js. Here, you will define the mapping between URL paths and your components.

import Vue from 'vue';
import VueRouter from 'vue-router';
import Dashboard from '@/components/Dashboard.vue';
import Settings from '@/components/Settings.vue';

// Initialize the plugin
Vue.use(VueRouter);

const routeDefinitions = [
  {
    path: '/',
    name: 'DashboardView',
    component: Dashboard
  },
  {
    path: '/settings',
    name: 'SettingsView',
    component: Settings
  }
];

const routerInstance = new VueRouter({
  mode: 'history', // Enables clean URLs without the hash (#)
  routes: routeDefinitions
});

export default routerInstance;

Injecting the Router into the Vue Instance

To make the router available throughout the application, import the configuration into your main.js file and link it to the root Vue instance.

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

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

Displaying Router Views

In your App.vue (the root component), use the <router-view> functional component. This serves as a dynamic slot where the router will inject the component corresponding to the current URL path.

<template>
  <div id="main-layout">
    <header>
      <nav>
        <!-- Navigation links would go here -->
      </nav>
    </header>
    <main>
      <!-- Dynamic content placeholder -->
      <router-view></router-view>
    </main>
  </div>
</template>

Tags: Vue.js Vue Router javascript Frontend Development

Posted on Tue, 11 Aug 2026 16:29:27 +0000 by rilitium