Learn how to use Vue Router for navigation in Vue.js applications. Discover step-by-step guidance on setting up Vue Router, dynamic routing, nested routes, and programmatic navigation. Perfect for beginners and developers preparing for Vue.js interviews!
Vue.js is like your LEGO set for building web applications. Each piece (or block) represents a part of your app, like a homepage, a profile page, or a contact page. But how do you move from one piece to another? That’s where Vue Router comes in! It’s like a map that guides users through your app.
In this blog, we’ll explore Vue Router and learn how to:
- Set up Vue Router for navigation.
- Use dynamic routing and nested routes.
- Navigate programmatically in Vue.js.
Table of Contents
What is Vue Router?
Vue Router is like a GPS for your Vue.js app. It helps users move between different pages (or components) without the page refreshing. This makes the app feel smooth and super-fast, like a single-page app (SPA).
Setting Up Vue Router for Navigation
Here’s how to set up Vue Router in your Vue.js project:
Step 1: Install Vue Router
Run this command in your project directory:
npm install vue-router
Step 2: Create Your Router File
Create a file named router.js
(or index.js
inside a router
folder) to define your routes.
Step 3: Define Your Routes
Routes tell Vue Router which component to display for a specific URL.
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';
const routes = [
{ path: '/', component: Home }, // Home page
{ path: '/about', component: About } // About page
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
Step 4: Use Vue Router in Your App
Import and use the router in your main.js
file:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
Now you can navigate between your components using <router-link>
like this:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
Dynamic Routing
Dynamic routing lets you use placeholders for routes. For example, imagine your app has many user profiles, and each has a unique id
. You can create a route like /user/:id
.
Here’s how:
const routes = [
{ path: '/user/:id', component: UserProfile }
];
Inside the UserProfile
component, you can access the id
with:
this.$route.params.id;
Nested Routes
Nested routes are like a tree. The main branch is the parent route, and smaller branches are child routes.
Example:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: UserProfile },
{ path: 'settings', component: UserSettings }
]
}
];
Here’s how users navigate:
/user/profile
→ Profile page/user/settings
→ Settings page
In the User
component, include a <router-view>
to display the child components:
<router-view></router-view>
Programmatic Navigation
Sometimes, you need to navigate users without them clicking a link. For instance, after submitting a form, you might want to send them to a “Thank You” page.
Here’s how you can navigate programmatically:
this.$router.push('/thank-you'); // Navigates to the Thank You page
You can also pass dynamic parameters:
this.$router.push({ path: `/user/${userId}` });
Interview Questions and Answers
Q1: What is Vue Router?
A: Vue Router is the official library for routing in Vue.js. It enables navigation between different pages (or components) in a single-page application (SPA).
Q2: What are dynamic routes in Vue Router?
A: Dynamic routes use placeholders (e.g., /user/:id
) to match URLs with specific patterns. These allow you to create routes for items like user profiles or product pages.
Q3: What is the purpose of nested routes?
A: Nested routes allow you to organize your app’s routes hierarchically. They help display child components inside parent components for better structure and navigation.
Q4: How do you navigate programmatically in Vue.js?
A: You can navigate programmatically using this.$router.push()
or this.$router.replace()
. These methods change the route without requiring a user to click a link.
Q5: What’s the difference between this.$router.push()
and this.$router.replace()
?
A:
this.$router.push()
: Adds a new entry to the history stack (allows going back).this.$router.replace()
: Replaces the current entry in the history stack (cannot go back).
Companies That Have Asked Vue Router Questions in Interviews
- Adobe
- Amazon
- TCS (Tata Consultancy Services)
- Infosys
- Cognizant
- Accenture
- Tech Mahindra
- Capgemini
Conclusion
Vue Router is an essential tool for creating dynamic and user-friendly Vue.js applications. Whether you’re creating simple navigation or handling complex nested routes, mastering Vue Router will make your apps smoother and more interactive.
With its features like dynamic routing, nested routes, and programmatic navigation, Vue Router empowers you to create scalable and efficient single-page applications. So start exploring and routing your way to success!