Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Vue Router Routes, RouterLink, Navigation Guards: Tutorial, Examples, FAQs & Interview Tips

What is Vue Router?

Vue Router is the official routing library for Vue.js. It enables client-side navigation in single-page applications - switching between views without a full page reload.

Vue Router - Setup, Routes, Navigation, Guards
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/HomeView.vue'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: '/about',
            name: 'about',
            // Lazy loading - code split
            component: () => import('../views/AboutView.vue')
        },
        {
            // Dynamic route parameter
            path: '/users/:id',
            name: 'user-detail',
            component: () => import('../views/UserDetail.vue'),
            props: true  // pass params as props
        },
        {
            // Nested routes
            path: '/dashboard',
            component: () => import('../views/Dashboard.vue'),
            meta: { requiresAuth: true },
            children: [
                { path: '', name: 'dashboard', component: () => import('../views/DashboardHome.vue') },
                { path: 'settings', name: 'settings', component: () => import('../views/Settings.vue') },
            ]
        },
        {
            // Redirect
            path: '/home',
            redirect: '/'
        },
        {
            // 404 catch-all
            path: '/:pathMatch(.*)*',
            name: 'not-found',
            component: () => import('../views/NotFound.vue')
        }
    ]
})

// Navigation guard - protect routes
router.beforeEach((to, from, next) => {
    const isLoggedIn = !!localStorage.getItem('token')

    if (to.meta.requiresAuth && !isLoggedIn) {
        next({ name: 'login', query: { redirect: to.fullPath } })
    } else {
        next()
    }
})

export default router
<!-- App.vue -->
<template>
  <nav>
    <!-- RouterLink - declarative navigation -->
    <RouterLink to="/">Home</RouterLink>
    <RouterLink to="/about">About</RouterLink>

    <!-- Named route -->
    <RouterLink :to="{ name: 'user-detail', params: { id: 42 } }">
      User 42
    </RouterLink>

    <!-- With query params -->
    <RouterLink :to="{ path: '/search', query: { q: 'vue', page: 1 } }">
      Search
    </RouterLink>

    <!-- Active class - automatically added when route matches -->
    <RouterLink to="/about" active-class="nav-active" exact-active-class="nav-exact">
      About
    </RouterLink>
  </nav>

  <!-- RouterView - renders the matched component -->
  <RouterView />
</template>
<!-- Using router composables -->
<template>
  <div>
    <p>User ID: {{ userId }}</p>
    <p>Current path: {{ route.path }}</p>
    <button @click="goBack">Back</button>
    <button @click="goToDashboard">Dashboard</button>
  </div>
</template>

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

const route  = useRoute()   // current route info
const router = useRouter()  // router instance

// Access route params
const userId = computed(() => route.params.id)

// Access query params
const searchQuery = computed(() => route.query.q)

// Programmatic navigation
function goBack() {
  router.back()
}

function goToDashboard() {
  router.push({ name: 'dashboard' })
}

function goToUser(id) {
  router.push({ name: 'user-detail', params: { id } })
}

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

Deep Dive: Vue Router in Real Projects

Understanding Vue Router is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Vue Router.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Vue Router.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Vue Router focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.