Exploring the New Vue Router: Navigating Your VueJS App with Ease
Last Updated :
08 Aug, 2024
Vue Router plays a crucial role in creating dynamic and engaging Single Page Applications (SPAs). The latest version, aligned with the release of Vue 3, introduces a range of exciting updates and enhancements. These improvements are designed to streamline the development process and provide new tools for building more sophisticated and efficient applications. In this article, we'll explore these new features and discuss how they can elevate your Vue 3 projects.
Exploring the New Vue Router: Navigating Your Vue.js App with EaseThese are the following topics that we are going to discuss:
Why Use Vue Router?
Vue Router plays an important role in building SPAs, as it enables navigation between different parts of the app without refreshing the page. This leads to a smoother and more efficient user experience. Moreover, Vue Router comes with features like nested routes, route guards, and the ability to navigate programmatically, making it a comprehensive tool for managing navigation and state in an application.
Installing from Vue CLI
First, install Vue CLI if you haven't already:
npm install -g @vue/cli
Create a new project:
vue create my-vue-app
cd my-vue-app
Add Vue Router:
vue add router
This command scaffolds the project and sets up the Vue Router with basic configurations.
Vue Router Basics
Once you've set up Vue Router, it's essential to understand its basic functionalities, such as installation, configuration, and navigation.
Installation:
To install Vue Router, use the following npm command:
npm install vue-router@next
Configuration:
Initialize the router instance in a dedicated router directory:
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
Navigation:
Use the RouterLink component for declarative navigation:
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
New Features in Vue Router 3
Vue Router 3 introduces several new features that enhance the development experience, especially with the introduction of Vue 3.
- Improved Composition API Support: Vue Router 3 integrates effortlessly with Vue 3's Composition API, enabling developers to manage route logic and guards within the setup function.
- Lazy Loading for Improved Performance: The implementation of lazy loading in Vue Router 3 is straightforward, which helps minimize initial load times by loading components only as needed.
- Navigation Guards: Navigation guards in Vue Router 3 allow for detailed control over navigation, facilitating tasks like authentication verification and data pre-loading.
- Improved Type Safety: By incorporating TypeScript, Vue Router 3 offers improved type safety, which helps in identifying and resolving potential errors early in development.
Beyond the Basics
In addition to its core features, Vue Router offers advanced functionalities that allow developers to build more sophisticated applications.
Named Routes: These routes provide a convenient way to reference routes, especially useful in programmatic navigation.
const routes = [
{ path: '/user/:id', name: 'User', component: User },
];
this.$router.push({ name: 'User', params: { id: 123 } });
Dynamic Segments: Dynamic segments in routes allow for more flexible and dynamic routing.
const routes = [
{ path: '/user/:id', component: User },
];
const userId = this.$route.params.id;
Lazy Loading for Improved Performance: As mentioned earlier, lazy loading reduces the initial load time by only loading components when needed.
Handling 404 Not Found: You can handle 404 errors gracefully by creating a catch-all route.
const routes = [
{ path: '/:catchAll(.*)', component: NotFound },
];
Custom Route Transitions: Add custom transitions to enhance the user experience during route changes.
<template>
<transition name="fade">
<router-view></router-view>
</transition>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
</style>
Route Meta Fields for Enhanced Route Information: Meta fields provide additional information for routes, useful for tasks like setting titles or managing access control.
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isLoggedIn()) {
next('/login');
} else {
next();
}
});
Programmatic Navigation: Use router.push and router.replace methods for programmatic navigation between routes.
// Navigating to a different route
this.$router.push('/dashboard');
// Replacing the current route
this.$router.replace('/profile');
Example: Below is the basic example of vue router.
JavaScript
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
JavaScript
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
</nav>
<main>
<router-view />
</main>
</div>
</template>
<script>
export default {
name: 'App',
};
</script>
<style>
nav {
display: flex;
gap: 10px; /* Adjust the gap value as needed */
}
</style>
JavaScript
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import AboutView from '../views/AboutView.vue';
const routes = [
{ path: '/', component: HomeView },
{ path: '/about', component: AboutView },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
JavaScript
<template>
<div>
<h1>Home Page</h1>
<p>Welcome to the home page.</p>
</div>
</template>
<script>
export default {
name: 'HomeView',
};
</script>
JavaScript
<template>
<div>
<h1>About Page</h1>
<p>Learn more about us on this page.</p>
</div>
</template>
<script>
export default {
name: 'AboutView',
};
</script>
Output:
Conclusion
Vue Router 3, with its new features and improvements, offers a comprehensive and efficient way to build SPAs with Vue 3. From enhanced Composition API support to performance improvements with lazy loading, Vue Router 3 is a must-have tool for modern Vue applications. Whether you're building a simple app or a complex one, Vue Router provides the flexibility and control needed to manage your application's navigation and state effectively.
Similar Reads
How to display loading screen when navigating between routes using Angular?
In this post, we will see how to display a loading screen when navigating from one component to another. When the user navigates through routes, the app may communicate with the backend to load some useful data, and it may produce some delay. At that time, if the user doesn't see anything on the scr
5 min read
How to Set URL Query Params in Vue with Vue-Router ?
Vue Router is a navigation library designed specifically for Vue.js applications. In this article, we will learn about the different methods of setting the URL query params in Vue with Vue-Router. Below is the list of all possible methods. Table of Content Using router-linkUsing push() methodUsing r
6 min read
Explain Route matching priority in VueJS ?
Route MatchingRoute Matching is the concept in which the Vue Router specifies which component is to be rendered according to the URL entered by the end user. If the user navigates to any specific URL, Vue Router checks for the defined routes and finds the match for that URL. It later compares the en
7 min read
Mastering React Routing: Learn Navigation and Routing in React Apps
React Routing is a technique used to handle navigation within a React application. It enables users to move between different views, pages, or components without refreshing the entire page, which is a key feature of Single Page Applications (SPAs). In this article, we will explore the essential conc
6 min read
How does React Router handle navigation in a React application?
React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. Let us create a simple application to React to understand how the React Router works Re
3 min read
Explain the purpose of Router services in Angular.
The Router service in Angular is an important component that enables navigation within our single-page application (SPA). It involves mapping URLs to different components or views within the application and rendering the appropriate content based on the requested URL. When a user interacts with navi
6 min read
Difference between NextJS Link vs useRouter in Navigating
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is navigation. Navigation is crucial for providing users w
3 min read
How to Hide the VueJS Syntax While the Page is Loading ?
Vue.js is a JavaScript framework used in building powerful and elegant user interfaces. In this article, we will learn how to hide the VueJS syntax while the page is loading. This approach ensures that users don't see the uncompiled Vue.js syntax during the initial page load, providing a smoother us
3 min read
Consuming a Rest API with Axios in Vue.js
Many times when building an application for the web that you may want to consume and display data from an API in VueJS using JavaScript fetch API, Vue resource, jquery ajax API, but a very popular and most recommended approach is to use Axios, a promise-based HTTP client. Axios is a great HTTP clien
2 min read
How to make your page scroll to the top when route changes?
Clicking the "About Us" button in a React application doesn't automatically scroll to the top of the page load, as react-router-dom only changes the route without resetting the scroll position; a separate functional component is needed to ensure the new page loads from the top when the route changes
3 min read