Welcome to The Coding College! In modern web applications, routing is a fundamental feature that allows users to navigate between different views or pages seamlessly. Vue provides a robust routing solution through Vue Router, enabling developers to manage navigation with ease.
In this guide, we’ll cover the basics of Vue routing, setting up Vue Router, defining routes, and advanced topics like navigation guards and dynamic routing.
What is Vue Router?
Vue Router is the official router for Vue.js, enabling single-page applications (SPAs) to mimic traditional multi-page applications by dynamically loading content without refreshing the page.
Key Features of Vue Router:
- Declarative routing using route definitions.
- Dynamic and nested routes for complex applications.
- Navigation guards for controlling access to routes.
- Lazy loading and code splitting for optimizing performance.
Setting Up Vue Router
Step 1: Install Vue Router
If you’re using Vue CLI, you can add Vue Router during the project setup. Otherwise, install it via npm or yarn:
npm install vue-router
Step 2: Create a Router File
Create a router.js
file (or index.js
inside a router
directory) to define your application’s routes.
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;
Step 3: Integrate Router with Vue App
Import and use the router in your main main.js
file.
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');
Defining Routes
Routes in Vue Router map URLs to components.
Example: Basic Routes
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
Named Routes
Using named routes makes navigation easier.
const routes = [
{ path: '/', name: 'Home', component: Home },
{ path: '/about', name: 'About', component: About }
];
Navigating Between Routes
Using <router-link>
<router-link>
is a component that renders anchor tags and enables navigation.
<template>
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
</template>
Using this.$router.push
You can programmatically navigate to a route using push()
.
this.$router.push('/about');
Dynamic Routes
Dynamic routes allow you to include parameters in your URLs, which can be used to fetch or display specific data.
Defining a Dynamic Route
const routes = [
{ path: '/user/:id', component: User }
];
Accessing Route Parameters
You can access route parameters via this.$route.params
.
User.vue
<template>
<div>
<h1>User ID: {{ userId }}</h1>
</div>
</template>
<script>
export default {
computed: {
userId() {
return this.$route.params.id;
}
}
};
</script>
Nested Routes
Vue Router supports nested routes for hierarchical views.
Example: Nested Routes
const routes = [
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'settings', component: Settings },
{ path: 'profile', component: Profile }
]
}
];
Usage in Templates
Use <router-view>
inside a parent component to render child routes.
<template>
<div>
<h1>Dashboard</h1>
<router-view></router-view>
</div>
</template>
Navigation Guards
Navigation guards are used to control access to routes based on conditions like authentication.
Example: Global Guard
router.beforeEach((to, from, next) => {
if (to.path === '/protected' && !isAuthenticated()) {
next('/login');
} else {
next();
}
});
Example: Per-Route Guard
const routes = [
{
path: '/protected',
component: Protected,
beforeEnter: (to, from, next) => {
if (isAuthenticated()) {
next();
} else {
next('/login');
}
}
}
];
Lazy Loading Routes
For performance optimization, you can lazy-load route components using dynamic imports.
const routes = [
{
path: '/about',
component: () => import('./views/About.vue')
}
];
Scroll Behavior
You can customize the scroll behavior when navigating between routes.
const router = createRouter({
history: createWebHistory(),
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
} else {
return { top: 0 };
}
}
});
Conclusion
Vue Router is a powerful tool for building single-page applications with seamless navigation and rich features like dynamic routing, nested routes, and navigation guards. By mastering Vue Router, you can create highly interactive and user-friendly web applications.
For more expert Vue tutorials, tips, and coding resources, visit The Coding College.