← Back to Tutorials

Vue Router Navigation

Dynamic routes, nested routing, and route guards for authentication. Build SPAs.

Setting up Vue Router

Vue Router is the official router for Vue.js. It enables building single-page applications with hash-based or history-based routing.

import { createRouter, createWebHistory } from 'vue-router'

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

Dynamic Routes

Dynamic routes let you capture URL parameters like /user/:id. This is useful for detail pages or user profiles.

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

Route Guards

Route guards control navigation, useful for authentication and authorization.

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    next('/login')
  } else {
    next()
  }
})

Nested Routes

Nested routes allow you to create hierarchical page structures with parent-child relationships.

const routes = [
  {
    path: '/parent',
    component: Parent,
    children: [
      { path: 'child', component: Child }
    ]
  }
]

Key takeaways

  • Use createWebHistory() for clean URLs
  • Dynamic routes capture parameters with :param
  • Route guards protect routes requiring auth
  • Lazy load routes for better performance
  • Nested routes create hierarchical page structures
  • Use meta fields for route-specific data