Skip to content

VueJS - Routing

Vue 3 - Client-Side Routing with Vue Router 4

Section titled “Vue 3 - Client-Side Routing with Vue Router 4”

Single-Page Applications (SPAs) need a way to navigate between different views or pages without a full page reload. Vue Router is the official library for handling routing in Vue applications. This chapter covers setting up and using Vue Router 4 (the version compatible with Vue 3).

Vue Router needs to be installed separately.

For projects managed with npm or yarn (typically set up with Vite or Vue CLI):

# NPM
npm install vue-router@4
# Yarn
yarn add vue-router@4

For simple projects or prototyping directly in HTML:

<!-- Include Vue 3 first -->
<script src="https://unpkg.com/vue@3"></script>
<!-- Then include Vue Router 4 -->
<script src="https://unpkg.com/vue-router@4"></script>

Setting up Vue Router involves defining your routes, creating a router instance, and telling your Vue application to use it.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue Router 4 Basic Example</title>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>
<style>
body { font-family: sans-serif; }
nav a { margin: 0 10px; text-decoration: none; color: blue; }
nav a.router-link-active { font-weight: bold; color: darkred; }
.view-content { margin-top: 20px; padding: 15px; border: 1px solid #ccc; background-color: #f9f9f9; }
</style>
</head>
<body>
<div id="app">
<h1>Vue Router Example</h1>
<nav>
<!-- Use router-link for navigation -->
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-link to="/users/1">User 1</router-link>
<router-link to="/users/2">User 2</router-link>
</nav>
<!-- Route outlet: Component matched by the route will render here -->
<router-view></router-view>
</div>
<script>
const { createApp } = Vue;
const { createRouter, createWebHashHistory, createWebHistory } = VueRouter; // Use VueRouter global in CDN context
// 1. Define Route Components (can be imported from files in a real app)
const Home = { template: '<div class="view-content"><h2>Home Page</h2><p>Welcome to the home page!</p></div>' };
const About = { template: '<div class="view-content"><h2>About Page</h2><p>Learn more about us here.</p></div>' };
const User = {
// Use Composition API to access route params
setup() {
const route = VueRouter.useRoute(); // Access route object
const userId = Vue.computed(() => route.params.id); // Make it computed for reactivity
return { userId };
},
template: '<div class="view-content"><h2>User Profile</h2><p>User ID: {{ userId }}</p></div>'
// Options API equivalent:
// computed: { userId() { return this.$route.params.id } }
};
// 2. Define Routes
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/users/:id', component: User } // Dynamic route with parameter 'id'
];
// 3. Create the Router Instance
const router = createRouter({
// Use hash history for simple example (/#/about)
// Use createWebHistory() for clean URLs (requires server config)
history: createWebHashHistory(),
routes, // short for `routes: routes`
});
// 4. Create and Mount the Vue App
const app = createApp({});
// Make sure to _use_ the router instance
app.use(router);
app.mount('#app');
</script>
</body>
</html>
  • Route Components: Define the Vue components that correspond to each view (Home, About, User). In real applications, these are typically Single File Components (SFCs).
  • Define Routes: Create an array (routes) where each object maps a path to a component. Dynamic segments like :id capture parts of the URL as parameters.
  • Create Router Instance: Use createRouter() to configure the router. Key options: * history: Specifies the history mode. createWebHashHistory() uses URL hashes (/#/about) which works without server configuration. createWebHistory() provides clean URLs (/about) but requires your server to handle fallback routes. * routes: The array of route definitions.
  • Use Router: Install the router instance into your Vue app using app.use(router). This makes router features available throughout the application.
  • <router-link>: This component renders an <a> tag for declarative navigation. The to prop specifies the target path.
  • <router-view>: This component acts as a placeholder where the matched route component will be rendered.
  • Accessing Route Params: Inside a component, you can access route information (like params) using VueRouter.useRoute() in the Composition API or this.$route in the Options API.
  • Active Link Styling: Vue Router automatically adds CSS classes (router-link-active and router-link-exact-active) to active <router-link> components, allowing easy styling.
  • to (required): The target route. Can be a string path ('/about') or a route location object ({ path: '/users/1' }, { name: 'user', params: { id: 1 } } - requires named routes).
  • replace: If true, navigation will call router.replace() instead of router.push(), meaning it won’t add a new entry to the history stack (user can’t go back).
  • active-class: Overrides the default ‘router-link-active’ class.
  • exact-active-class: Overrides the default ‘router-link-exact-active’ class.
  • custom: Allows you to customize the rendered element and control navigation programmatically via the v-slot API. Example: <router-link to="/about" custom v-slot="{ navigate, href }"><button :href="href" @click="navigate">Custom Button</button></router-link>

Note: The tag and event props from Vue Router 3 are deprecated/removed in Vue Router 4. Use the custom prop with v-slot for similar functionality.

Besides <router-link>, you can navigate programmatically using the router instance.

// Inside Composition API setup function:
import { useRouter } from 'vue-router';
const router = useRouter();
function goToAbout() {
router.push('/about');
}
function goToUser(userId) {
router.push({ name: 'user', params: { id: userId } }); // Using named route
}
function goBack() {
router.go(-1);
}
// Inside Options API component method:
methods: {
goToAbout() {
this.$router.push('/about');
},
// ... etc
}

Use useRouter() in Composition API or this.$router in Options API to access the router instance and its methods (push, replace, go).

Vue Router offers many more features like named routes, nested routes, navigation guards, lazy loading, and more. Refer to the Official Vue Router 4 Documentation for comprehensive details.