How to Use Vue Router in Vue 3 with Composition API

Modern web applications need to have smooth navigation between pages and sections. The users expect fast and smooth navigation within applications. They want to move between pages without delays or full-page reloads. Creating this kind of seamless experience requires the right tools and structure behind the scenes.

Vue Router is one of those essential tools. It helps transform your Vue app into a dynamic single-page application where content updates without refreshing the page. If you’re just starting with Vue or planning to hire Vue.js developers, learning how to make Vue Router with Composition API work is an important skill. This blog will break this concept down in a simple, beginner-friendly way without diving too deep into complex code.

What Makes Vue Router Essential in Vue 3?

As web applications become more dynamic and user-focused, delivering smooth navigation is no longer optional. Vue Router plays a critical role in achieving that by enabling single-page application (SPA) behavior in Vue.

how to use vue router in vue 3

Vue Router makes navigation feel smooth by only updating the parts of the page that actually change, which is better than reloading everything from scratch. This means pages load faster and feel more seamless to the user. When you use Vue Router alongside the Composition API, it gets even better; the code becomes cleaner, more efficient, and easier to manage, which helps your app run more smoothly overall.

Here’s why Vue Router is such a powerful tool in Vue 3:

  • Single-Page Navigation: Eliminates full page reloads by updating only the relevant components.
  • Improved Performance: Delivers faster load times and a more responsive feel for users.
  • Better Code Structure: The Composition API allows routing logic to be written in a cleaner, modular way.
  • Future-Proof and Backward-Compatible: Works seamlessly with Vue 3’s Composition API while still supporting Vue 2’s Options API.
  • Scalable Architecture: Makes it easier to manage routes in larger applications with nested and dynamic routes.
  • Flexible Integration: Supports features like route guards, lazy loading, and named views with ease.

This combination of power, flexibility, and ease of use is what makes Vue Router a must-learn for any Vue 3 developer. hire Vue.js developers with skills in such technologies to get started.

How to Setup Vue Router with Composition API in Your Vue 3 Project

Step 1. Vue Router Installation and Configuration

  • Install Vue Router using npm or yarn.
  • Set up the routes in a config file.
  • Create a list of routes, connecting each URL path to a targeted Vue Component. (Home Page, User Profiles and more)
  • Connect the router to the Vue.js app.

Step 2: Connecting Router to Your App

This connection is established in the main app file with a simple method call. All components in your Vue.js app can access routing features. It is similar to adding a GPS system to a car. Once connected, it can be navigated anywhere without having to figure out directions each time.

Understanding Route Definitions and Components

Step 3: Basic Route Configuration

Routes are simple objects that match URLs to components. It reflects the pages your user visits. When someone would click on About, your router would show the About component, and so on. The routers can be given personalized names, so you don’t have to remember the exact URL. You can use easier names such as ‘home’ or ‘userProfile’ in the code.

Step 4: Dynamic Routes and Parameters

Dynamic routes are useful for situations where a certain part of URL changes. For example, user profiles can have URLs ending with /user/123 or so. The numeral part of the URL changes for each profile, but the route remains constant. Such changeable parts are known as parameters.

Step 5: Nested Routes Structure

Some pages have sub-pages, like a dashboard with different sections. Nested routes help organize these relationships. The primary dashboard route can have child routes for settings, reports and user management.

This structure mirrors how you organize your components. Parent routes show layout components, while child routes show specific content within that layout.

Step 6: Understanding Router-View Component

The <router-view> component works like a placeholder. It shows different content as per the current URL. Users insert it in the template they want the page content to appear.

Think of it as a picture frame that automatically changes the picture based on which room you’re in. The frame stays the same, but the content changes as you navigate around your app.

Router-link components create navigation links that work with Vue Router. They look like regular links but don’t cause page refreshes. Instead, they smoothly transition between different views.

These links automatically get special CSS classes when they match the current page. This makes it easy to style active navigation items differently, like highlighting the current page in your menu.

Mastering the Composition API with Vue Router

Step 8: Core Composables Overview

The Composition API gives you two main tools for working with routes: useRouter and useRoute. These replace the old this.$router and this.$route patterns with something cleaner and more explicit.

useRouter gives you navigation methods, while useRoute provides information about the current route.

Step 9: Using useRoute for Route Information

The useRoute composable is your direct line to whatever’s happening with the current route. You get all the good stuff – URL parameters, query strings, you name it. Plus it keeps itself updated automatically when someone navigates around, so your component never falls behind.

javascript
import { useRouter, useRoute } from ‘vue-router’
export default {
  setup() {
    const router = useRouter()
    const route = useRoute()
   
    const goHome = () => router.push(‘/’)
    const userId = route.params.id
 
    return { goHome, userId }
  }
}

How to Use Programmatic Navigation in Vue 3 Composition API

Vue.js Navigation Methods and Techniques

Sometimes the users need to be navigated manually, like after they submit a form or complete a purchase. The router provides methods to do this through code rather than user clicks.

The push method adds a new page while the replace method updates the current page in history instead of adding a new one.

Navigation Guards Integration

Navigation guards with the composition API act like security checkpoints that run before a route changes. You can use them to check if a user is logged in, has the right permissions, or if some data needs to be loaded before showing a page.

If you’re building apps with Vuejs development services, these guards are key to making your app both secure and smooth. They make sure users only see what they’re allowed to, at the right time, based on their access and the current state of the app.

Dynamic Routing and Route Parameters

Parameter Handling Strategies

Dynamic routing in Vue 3 makes your app flexible enough to handle variable content. Instead of creating separate routes for every possible page, you use patterns that match multiple URLs and extract the relevant information.

Route parameters appear automatically in your components through the route object. These parameters update when the route changes, allowing your component to respond appropriately.

Watching Parameter Changes

Sometimes, users stay on the same route but change the parameters — like switching between different user profiles. In these cases, your component needs to react to those changes and update its data.

The Composition API’s watch function is great for this as it lets you watch route parameters and run code whenever they change, so you can fetch new data or update the component’s state without reloading the page.

Concluding Lines

Mastering Vue Router with Composition API helps you build smooth, scalable, and user-friendly applications. With clean routing logic and dynamic navigation, your Vue 3 apps become faster, easier to manage, and ready for real-world complexity and growth.

author avatar
Elita Torres

Leave a Comment