Vue.js Routing
Vue doesn't include routing by default, but the official Vue Router library makes it easy to build single-page applications (SPAs).
Basic Routing Example
Below is a simple routing setup with two pages: Home and About.
Dynamic Routes Example
Example with parameterized routes:
How Vue Router Works
Core Components
- <router-view>: Renders the matched component
- <router-link>: Declarative navigation
- $router: Programmatic navigation methods
- $route: Current route information
Navigation Methods
this.$router.push('/path')- Navigate to paththis.$router.replace('/path')- Replace current historythis.$router.go(-1)- Go backthis.$router.go(1)- Go forward
Installation and Setup
1. Install Vue Router
npm install vue-router@4
2. Router Configuration
// router.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;3. Main Application Setup
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');Safe Route Access Patterns
Option 1: Safe Navigation with Conditional Checks
// Always check if $route exists
<template>
<div>
<p>Current path: {{ $route ? $route.path : '/' }}</p>
<p>User ID: {{ $route && $route.params ? $route.params.id : 'N/A' }}</p>
</div>
</template>Option 2: Using Computed Properties
<template>
<div>
<p>Current path: {{ currentPath }}</p>
<p>User ID: {{ userId }}</p>
</div>
</template>
<script>
export default {
computed: {
currentPath() {
return this.$route ? this.$route.path : '/';
},
userId() {
return this.$route && this.$route.params ? this.$route.params.id : 'N/A';
}
}
}
</script>Option 3: Route Props (Recommended)
// router.js - Pass params as props
{
path: '/user/:id',
component: UserProfile,
props: true // Pass route.params as props
}
// UserProfile.vue - Use props instead of $route
<template>
<div>
<p>User ID: {{ id }}</p>
</div>
</template>
<script>
export default {
props: ['id'] // Safer than using $route.params.id
}
</script>Common Routing Patterns
Best Practice: Always use named routes and pass parameters as props for better maintainability and type safety.
Summary
- Use conditional checks when accessing
$route - Prefer passing route parameters as props
- Use named routes for better maintainability
- Always handle potential undefined values
- Use navigation guards for complex routing logic