How to redirect on page not found with Vue Router?

Sometimes, we want to redirect on page not found with Vue Router.

In this article, we’ll look at how to redirect on page not found with Vue Router.

How to redirect on page not found with Vue Router?

To redirect on page not found with Vue Router, we can use the '*' path to match all routes that aren’t listed in the routes definition.

For instance, we write

const router = new VueRouter({
  mode: "history",
  routes: [
    { path: "/", component: HomeComponent },
    // ...
    { path: "*", component: PageNotFound },
  ],
});

to create a VueRouter instance with

{ path: "*", component: PageNotFound }

in routes to match all route paths` that aren’t listed above it.

PageNotFound is a component like any other component.

Conclusion

To redirect on page not found with Vue Router, we can use the '*' path to match all routes that aren’t listed in the routes definition.