Vue Router

Language: JavaScript

Routing

Vue Router was created by the Vue.js core team to handle routing in single-page applications (SPAs). It integrates tightly with Vue's reactive system, allowing developers to easily manage navigation, URL parameters, and programmatic routing with minimal setup.

Vue Router is the official router for Vue.js, enabling navigation between components and views in a Vue application. It provides declarative routing, nested routes, dynamic route matching, and navigation guards.

Installation

npm: npm install vue-router
yarn: yarn add vue-router

Usage

Vue Router allows you to define routes mapping URLs to components. You can use `<router-link>` for navigation and `<router-view>` to render the matched component. It supports nested routes, dynamic segments, programmatic navigation, and route guards for authentication or authorization.

Setting up basic routes

import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';

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

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

export default router;

Defines a router with two routes (`/` and `/about`) mapping to Vue components.

Using router in main app

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

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

Integrates Vue Router into the main Vue application.

Navigation links

<template>
  <nav>
    <router-link to='/'>Home</router-link>
    <router-link to='/about'>About</router-link>
  </nav>
  <router-view></router-view>
</template>

Uses `<router-link>` for navigation and `<router-view>` to render the current route component.

Dynamic route parameters

const routes = [
  { path: '/user/:id', component: User }
];

// Accessing parameter in component
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
console.log(route.params.id);
</script>

Defines a route with dynamic segments and accesses route parameters in a component.

Nested routes

const routes = [
  { path: '/dashboard', component: Dashboard, children: [
      { path: 'stats', component: Stats },
      { path: 'settings', component: Settings }
  ]}
];

Sets up nested routes inside a parent route.

Navigation guards

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

Implements a global navigation guard to protect routes that require authentication.

Programmatic navigation

<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
function goHome() {
  router.push('/');
}
</script>
<button @click="goHome">Go Home</button>

Demonstrates navigating programmatically using the `router.push()` method.

Error Handling

NavigationDuplicated: Occurs when trying to navigate to the current route. Use `router.push()` with a catch or check if the route is different.
404 Page Not Found: Add a wildcard route (`path: '/:pathMatch(.*)*'`) to display a NotFound component for unmatched URLs.
Dynamic parameter undefined: Ensure the route parameter is correctly defined and passed in the URL.

Best Practices

Use `createWebHistory()` for clean URLs without hashes in production.

Keep route definitions modular and organize them in a separate router file.

Use nested routes for complex layouts with multiple sub-components.

Use meta fields to store route-specific information like authentication requirements.

Leverage navigation guards to protect sensitive routes.