Advanced Routing Techniques with Vue Router 4

Introduction

Vue Router 4 is the official and advanced official routing library for embedding views in Vue.js applications that offer interactive user experiences.

Cooperative linear navigation is provided, but to advance it is necessary to learn how to use the advanced features of routing. This post discusses these methods and provides plenty of examples helping you to enhance your applications in Vue.js.

1. Dynamic Routing

Dynamic routing is a core feature of Vue Router that allows you to create routes with dynamic segments. These prove useful when attempting to change to other views as defined by dynamic parameters like user ID or product category, etc.

Example:

const routes = [

  {

    path: '/user/:id',

    component: UserProfile,

  },

];

In the example above, :id is a dynamic segment. Upon the user moving to /user/123, this will trigger a rendering of the UserProfile component, whereupon 123 can be accessed as this.$route.params.id from within that component’s code.

2. Nested Routes

Nested routes enable you to structure your views hierarchically, which is perfect for creating layouts with sidebars, headers, or other nested components. This technique allows you to define child routes within a parent route.

Example:

const routes = [

  {

    path: '/dashboard',

    component: DashboardLayout,

    children: [

      {

        path: 'profile',

        component: Profile,

      },

      {

        path: 'settings',

        component: Settings,

      },

    ],

  },

];

 

In this example, the DashboardLayout component will always be rendered, and the Profile or Settings component will be rendered within it depending on the nested route.

3. Route Guards

An access control mechanism based on conditions for certain routes is provided by route guards. Three types of guards are offered by the Vue Router: global guards, per-route guards and in-component guards.

Example (Per-Route Guard):

const routes = [

  {

    path: '/admin',

    component: AdminPanel,

    beforeEnter: (to, from, next) => {

      if (isUserAuthenticated()) {

        next();

      } else {

        next('/login');

      }

    },

  },

];

 

Here, the beforeEnter guard checks if the user is authenticated before allowing access to the admin panel.The absence of a valid user session will lead him to the login page.

4. Lazy Loading Routes

Splitting the application into smaller chunks is a technique to enhance its performance called lazy loading. It is possible to perform lazy loading of routes in Vue Router, so that when visited one of them, the component loading will be delayed.

 

Example:

const routes = [

  {

    path: '/about',

    component: () => import('./views/About.vue'),

  },

];

 

In this example, the About component will only be loaded when the /about route is visited.

5. Named Views

Named views allow you to display multiple views in the same route. This is useful when you want to render different components in different sections of your layout.

 

Example:

const routes = [

  {

    path: '/dashboard',

    components: {

      default: DashboardMain,

      sidebar: DashboardSidebar,

    },

  },

];

 

Here, DashboardMain will be rendered in the default , and DashboardSidebar will be rendered in a named .

6. Programmatic Navigation

Programmatic navigation allows you to navigate to different routes in your application using JavaScript. This is useful for navigation based on specific conditions or events, such as form submissions or button clicks.

 

Example:

methods: {

  goToProfile() {

    this.$router.push({ path: `/user/${this.userId}` });

  },

}

The method goToProfile programmatically navigates to the user’s profile page.

 

7. Handling 404 Errors:

404 Errors Management with a Catch-All RouteHandling 404 errors is critical for a good user experience altogether. In Vue Router, one can set up a catch-all route which would match every undefined path.

Example:

const routes = [

  // other routes...

  {

    path: '/:pathMatch(.*)*',

    component: NotFound,

  },

];

 

This route will catch any paths that don’t match the defined routes and display the NotFound component.

 

8. Scroll Behavior

You can personalize how scrolling is conducted when moving from one route to another using Vue Router. This function can be of great help in instances where we want to maintain scrolling positions or to ensure that there always is a return to the top of the page whenever we switch routes.

 

Example:

const router = new VueRouter({

  routes,

  scrollBehavior(to, from, savedPosition) {

    if (savedPosition) {

      return savedPosition;

    } else {

      return { top: 0 };

    }

  },

});

 

In this example, the scroll position is preserved if available; otherwise, the page scrolls to the top.

Conclusion

Vue Router 4 features a comprehensive list of advanced routing methods that can be quite useful in enhancing your Vue.js applications. By learning and implementing these techniques – dynamic routing, nested routes, route guards, lazy loading, named views, programmatic navigation, handling of the 404 page and scrolling – you will be able to design SPAs that are faster, safer, and far more pleasant to use. It does not matter if you go for a small project or a bigger one, such techniques will allow you to write high quality and maintainable code.

Follow Us On

Registered Office

CHG IT CONSULTANCY PVT LTD

STPI Technology Incubation Centre,
2nd Floor, No.5, Rajiv Gandhi Salai,
Taramani, Chennai – 600113,
Tamil Nadu, INDIA

Parent Office

CIC Corporation

2-16-4 Dogenzaka, Shibuya-ku,
Nomura Real Estate,
Shibuya Dogenzaka Building,
Tokyo 150-0043, JAPAN

  +81 03-3496-1571
AboutUs

CHG IT Consultancy Pvt. Ltd. is a subsidiary of CIC Holdings Co. Ltd. Japan. Our company is focused on IT related solutions to reap the benefits of global popularity of Software Industry.

Registered Office
CHG IT CONSULTANCY PVT LTD

STPI Technology Incubation Centre,
2nd Floor, No.5, Rajiv Gandhi Salai,
Taramani, Chennai – 600113,
Tamil Nadu, INDIA

CIC Corporation

2-16-4 Dogenzaka, Shibuya-ku,
Nomura Real Estate,
Shibuya Dogenzaka Building,
Tokyo 150-0043, JAPAN

+81 03-3496-1571