Vue.js Routing (Vue Router)

Routing is an essential part of modern Single Page Applications (SPAs). It allows users to navigate between different views without reloading the page, ensuring a seamless and interactive user experience. Vue.js handles routing through the Vue Router, which is the official router for Vue.js.

Introduction to Vue.js Routing

In traditional web applications, navigating between different pages usually involves loading new HTML files from the server. However, in modern SPAs, the page is only loaded once, and JavaScript is responsible for switching between different views.

Vue Router facilitates this by providing tools to map URLs to components, handle navigation, and manage dynamic URLs.

Introduction to Vue.js Routing, Vue Router

Setting Up Vue Router

1. Installing Vue Router

To use Vue Router in a Vue.js project, you first need to install it:

				
					npm install vue-router
				
			

Once installed, you need to import and register it within your Vue application.

2. Basic Setup

In your main.js file:

				
					import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import Home from './components/Home.vue';
import About from './components/About.vue';

Vue.use(VueRouter);

const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
];

const router = new VueRouter({
  routes
});

new Vue({
  render: h => h(App),
  router
}).$mount('#app');

				
			

Explanation:

  • Vue.use(VueRouter): This installs Vue Router as a plugin.
  • routes: An array of route objects where path is the URL and component is the Vue component to be rendered when the path is matched.
  • new VueRouter: This creates a new instance of the Vue Router with the defined routes.
  • router: The router instance is injected into the root Vue instance.

3. Adding Router Links

Once you’ve set up the router, you can add navigation links in your application using the <router-link> component:

				
					<template>
  <div>
    <nav>
      <router-link to="/">Home</router-link>
      <router-link to="/about">About</router-link>
    </nav>
    <router-view></router-view>
  </div>
</template>

				
			

Explanation:

  • <router-link>: This component generates an anchor tag (<a>) that navigates to the specified path.
  • <router-view>: This component renders the component matched by the current route.

Output:

Clicking on the links will dynamically load the Home or About component without reloading the page.

Dynamic Routing

Dynamic routing allows you to pass parameters through the URL. This is useful for things like user profiles, where each profile has a unique ID.

1. Defining Dynamic Routes

You can define dynamic routes by using a colon (:) to denote a dynamic segment.

				
					const routes = [
  { path: '/user/:id', component: User }
];
				
			

2. Accessing Route Parameters

In your component, you can access the route parameters via this.$route.params:

				
					<template>
  <div>
    <h1>User ID: {{ $route.params.id }}</h1>
  </div>
</template> <script type="litespeed/javascript">export default{}</script> 
				
			

Output:

If you navigate to /user/123, it will display User ID: 123.

Nested Routes

Sometimes, you want to render components inside other components based on the route. For example, if you’re building a dashboard, you might want a nested layout with different sections like “Profile” and “Settings.”

1. Defining Nested Routes

Nested routes allow you to structure your routes hierarchically:

				
					const routes = [
  {
    path: '/user/:id',
    component: User,
    children: [
      { path: 'profile', component: UserProfile },
      { path: 'settings', component: UserSettings }
    ]
  }
];

				
			

2. Using <router-view> for Nested Routes

In your parent component (User), use <router-view> to render the nested components.

				
					<template>
  <div>
    <h1>User Page</h1>
    <router-view></router-view>
  </div>
</template>

				
			

Output:

Navigating to /user/123/profile will render the UserProfile component inside the User component.

Navigation Guards

Vue Router provides navigation guards to control access to routes. These can be useful for tasks like authentication checks.

Global Guards

You can define global guards that run before every route change:

				
					const router = new VueRouter({ routes });

router.beforeEach((to, from, next) => {
  if (to.path === '/admin' && !isAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});
				
			

Explanation:

  • to: The target route being navigated to.
  • from: The current route being navigated away from.
  • next: A function that must be called to resolve the navigation. You can redirect to another route by calling next('/path').

Programmatic Navigation

Besides using <router-link>, you can navigate programmatically in Vue Router using the this.$router.push() method.

Example

				
					methods: {
  goToHome() {
    this.$router.push('/');
  }
}

				
			

This allows you to navigate to different routes from within methods, making it more flexible to handle user interactions.

Route Meta Fields

You can define meta fields in your routes for custom logic. For example, marking routes that require authentication:

				
					const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  }
];

				
			

In your navigation guard, you can check for the requiresAuth meta field:

				
					router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});
				
			

Lazy Loading Routes

As your application grows, loading all the components at once can slow down the app. Vue Router supports lazy loading to load components only when they are needed.

Lazy Loading with Dynamic Imports

To lazy load a route, you can use dynamic imports:

				
					const routes = [
  {
    path: '/about',
    component: () => import('./components/About.vue')
  }
];

				
			

This ensures that the About component is only loaded when the user navigates to the /about route.

Handling 404 and Redirects

It’s common to provide users with meaningful messages when they navigate to a route that doesn’t exist or handle redirects.

1. Redirects

You can redirect a route to another path using the redirect property:

				
					const routes = [
  { path: '/home', redirect: '/' }
];

				
			

2. Catch-All Route for 404

To handle 404 errors, use a catch-all route with *:

				
					const routes = [
  { path: '*', component: NotFound }
];

				
			

Advanced Routing with Named Views

Sometimes you may want to display multiple components in different sections of the page when navigating to a single route. This can be done using named views.

1. Defining Named Views

				
					const routes = [
  {
    path: '/user/:id',
    components: {
      default: User,
      sidebar: UserSidebar
    }
  }
];

				
			

2. Rendering Named Views

You need to specify where each view should be rendered in your template:

				
					<template>
  <div>
    <router-view></router-view>
    <router-view name="sidebar"></router-view>
  </div>
</template>

				
			

Output:

  • The User component is rendered in the default view, and UserSidebar is rendered in the sidebar view.

Vue Router with Vuex

Vue Router and Vuex often work together in large applications. For example, you might need to trigger Vuex actions based on route changes or store the current route’s state in Vuex.

Example: Syncing Vue Router with Vuex

				
					const store = new Vuex.Store({
  state: {
    currentRoute: ''
  },
  mutations: {
    setRoute(state, route) {
      state.currentRoute = route;
    }
  }
});

router.beforeEach((to, from, next) => {
  store.commit('setRoute', to.path);
  next();
});

				
			

Vue Router is a powerful tool for building modern single-page applications with Vue.js. It allows you to create dynamic, nested, and complex navigation structures while maintaining a clear and maintainable architecture. By using Vue Router efficiently, you can ensure that your application's navigation is seamless and intuitive for users. Happy Coding!❤️

Table of Contents