Core Routing Features Explained
🎯 Introduction
Understanding the core routing features in Vue 2 helps you build applications with multiple views and handle complex navigation and display requirements. This article covers dynamic routes, nested routes, redirects, and aliases, along with programmatic navigation and the trade-offs of different routing modes. These features are useful in everyday projects.
🌀 Dynamic Route Matching: Routes with Parameters (such as /user/:id)
Page content often depends on URL parameters. For example, a user details page might use a user ID in its path. Vue Router in Vue 2 supports dynamic route matching, allowing path parameters to identify different data.
Defining a Dynamic Route
const routes = [
{
path: '/user/:id',
component: UserDetail,
},
];
Here, :id is a placeholder. When you visit /user/123, 123 is available to the component as a route parameter.
Accessing Dynamic Parameters
Inside a component, use $route.params to access dynamic parameters:
<template>
<div>
<h2>User ID: {{ userId }}</h2>
</div>
</template>
<script>
export default {
computed: {
userId() {
return this.$route.params.id;
},
},
};
</script>
🏗️ Nested Routes: Displaying Multiple Levels of Pages
Nested routes display child components within a parent component to create a hierarchy of views. For example, a product management page in an e-commerce admin application might contain several subpages.
Configuring Nested Routes
const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{
path: 'stats',
component: Stats,
},
{
path: 'settings',
component: Settings,
},
],
},
];
Visiting /dashboard/stats displays the Stats component inside Dashboard.
Using <router-view> in the Parent Component
The parent component needs a <router-view> to render the component matched by the child route.
<template>
<div>
<h1>Admin Dashboard</h1>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'Dashboard',
};
</script>
/ if it should be relative to its parent. A leading slash makes it a root path.🔄 Redirects: Configuring redirect
Use a redirect when visiting one path should automatically navigate to another.
Redirect Example
const routes = [
{
path: '/home',
redirect: '/dashboard',
},
];
Visiting /home automatically redirects to /dashboard.
🎭 Aliases (alias): Multiple Paths for One Component
Use alias when multiple paths should display the same component while keeping the requested URL unchanged.
Alias Example
const routes = [
{
path: '/profile',
component: Profile,
alias: '/my-profile',
},
];
Both /profile and /my-profile render the Profile component without changing the requested URL in the address bar.
🕹️ Programmatic Navigation: Using router.push() and router.replace()
Besides using <router-link> in templates, you can navigate from code to respond more flexibly to user actions.
router.push()
Navigates to a new route and adds an entry to the browser's history, allowing the user to go back afterward.
this.$router.push('/dashboard');
You can also pass an object:
this.$router.push({ path: '/user/123' });
router.replace()
Navigates to a new route by replacing the current history entry, without adding a new one.
this.$router.replace('/login');
🗺️ HTML5 History Mode
Vue Router in Vue 2 uses hash mode by default, routing through the # fragment in the URL. History mode uses the HTML5 History API for cleaner URLs.
How Hash Mode Works
The browser does not send the # fragment or anything after it to the server. The client uses the path after # to render the corresponding page.
Example URL:
http://example.com/#/user/123
How History Mode Works
APIs such as history.pushState update the URL, while client-side routing handles navigation and renders the matching content. The URL looks like a regular path.
Example URL:
http://example.com/user/123
Comparing Use Cases
- Hash mode offers broader compatibility and requires no server configuration, making it suitable for static hosting and simple applications.
- History mode provides cleaner URLs for projects concerned with SEO, but requires server support to serve the entry page for application routes.
index.html for application routes so that refreshing a page does not return a 404.❓ Questions and Answers
Q1: Is the component automatically recreated when dynamic route parameters change?
No. The component instance is reused. Watch $route for changes or handle them in a navigation guard.
Q2: What happens if a nested route's child path starts with /?
It is treated as a root path, so it will not match the intended parent-relative URL. Omit the leading / for a relative child path.
Q3: How do you prevent 404 errors when refreshing in history mode?
Configure the server to fall back to index.html for application route requests.
🧪 Exercises
Exercise 1: Build a Dynamic User Page
Create a route at /profile/:username whose component displays the username from the URL.
const routes = [
// Add the route configuration here
];
<template>
<div>
<h2>Username: {{ username }}</h2>
</div>
</template>
<script>
export default {
computed: {
username() {
// Access the route parameter
},
},
};
</script>
Exercise 2: Display Nested Menu Pages
Define a /settings route with two child routes, /settings/account and /settings/privacy, each displaying different content.
const routes = [
// Configure the parent and child routes
];
<template>
<div>
<h1>Settings</h1>
<!-- Render the child route component here -->
</div>
</template>
<script>
export default {
name: 'Settings',
};
</script>
🎉 You now know how to use dynamic route matching, nested routes, redirects, aliases, programmatic navigation, and history and hash modes in Vue 2! Keep practicing to become more comfortable building client-side navigation.
Getting Started with Vue Router
Learn what single-page applications are, how client-side routing works, and how to install, configure, and use Vue Router in a Vue 2.0 project.
Navigation Guards and Route Metadata
Learn to use navigation guards, route metadata, and page transitions for advanced routing in Vue 2.
