Vue Routing

Navigate between pages in Vue applications

🧭 What is Vue Router?

Vue Router is the official routing library for Vue.js. It enables navigation between different views in single-page applications, manages browser history, and supports dynamic routes, nested routes, and route guards for authentication.


// Basic Router Setup
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

export default router
                                    

Key Routing Concepts

🛣️

Routes

Define URL paths and components

{ path: '/home', 
  component: Home }
🔗

Router Links

Navigate between routes

<router-link to="/about">
  About
</router-link>
📍

Dynamic Routes

Routes with parameters

{ path: '/user/:id', 
  component: User }
🛡️

Route Guards

Protect routes with logic

beforeEnter: (to, from) => {
  // Check auth
}

🔹 Basic Router Setup

Install and configure Vue Router in your application:

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
import Contact from '../views/Contact.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  },
  {
    path: '/contact',
    name: 'Contact',
    component: Contact
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App)
  .use(router)
  .mount('#app')

🔹 Router View and Links

Display routed components and create navigation:

<!-- App.vue -->
<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link>
      <router-link to="/about">About</router-link>
      <router-link to="/contact">Contact</router-link>
    </nav>
    
    <!-- Routed component displays here -->
    <router-view />
  </div>
</template>

<style>
nav {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  background: #f0f0f0;
}

nav a {
  text-decoration: none;
  color: #333;
}

nav a.router-link-active {
  color: #42b983;
  font-weight: bold;
}
</style>

🔹 Dynamic Routes with Parameters

Create routes that accept dynamic parameters:

// router/index.js
const routes = [
  {
    path: '/user/:id',
    name: 'User',
    component: User
  },
  {
    path: '/post/:id/edit',
    name: 'EditPost',
    component: EditPost
  }
]
<!-- User.vue -->
<template>
  <div>
    <h2>User Profile</h2>
    <p>User ID: {{ userId }}</p>
    <p>Full Route: {{ $route.path }}</p>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const userId = computed(() => route.params.id)
</script>

<!-- Navigate to dynamic route -->
<router-link to="/user/123">User 123</router-link>
<router-link :to="`/user/${userId}`">User Profile</router-link>

🔹 Programmatic Navigation

Navigate using JavaScript instead of links:

<template>
  <div>
    <button @click="goToAbout">Go to About</button>
    <button @click="goToUser(456)">Go to User 456</button>
    <button @click="goBack">Go Back</button>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'

const router = useRouter()

function goToAbout() {
  router.push('/about')
}

function goToUser(id) {
  router.push({ name: 'User', params: { id } })
}

function goBack() {
  router.back()
}

// Other navigation methods
function goForward() {
  router.forward()
}

function replaceRoute() {
  router.replace('/home') // No history entry
}
</script>

🔹 Nested Routes

Create child routes within parent routes:

// router/index.js
const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    children: [
      {
        path: 'profile',
        component: Profile
      },
      {
        path: 'settings',
        component: Settings
      }
    ]
  }
]
<!-- Dashboard.vue -->
<template>
  <div class="dashboard">
    <h1>Dashboard</h1>
    <nav>
      <router-link to="/dashboard/profile">Profile</router-link>
      <router-link to="/dashboard/settings">Settings</router-link>
    </nav>
    
    <!-- Child routes render here -->
    <router-view />
  </div>
</template>

🔹 Route Guards

Protect routes with authentication checks:

// router/index.js
const routes = [
  {
    path: '/admin',
    component: Admin,
    beforeEnter: (to, from) => {
      const isAuthenticated = checkAuth()
      if (!isAuthenticated) {
        return '/login'
      }
    }
  }
]

// Global guard
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !isLoggedIn()) {
    return { name: 'Login' }
  }
})

// Route with meta
{
  path: '/profile',
  component: Profile,
  meta: { requiresAuth: true }
}

🧠 Test Your Knowledge

Which component displays the matched route component?