Vue 3 - Catch All Redirect (Default Route) with Vue Router
Tutorial built with Vue 3.2.45 and Vue Router 4.1.6
This is a super quick post to show how to create a catch all (default) redirect to the home page (/
) in a Vue 3 app with Vue Router. The redirect runs when a request is made to a route that doesn't exist in the Vue 3 app.
The way to do it is with a custom parameter catch all regular expression like this:
{ path: '/:pathMatch(.*)*', redirect: '/' }
The path
is a custom route parameter (:pathMatch
) followed by a catch all regex ((.*)*
) to match all paths. When a request matches this route it is redirected to the home page ('/'
) with the redirect
property.
Example Vue 3 Router with Catch All Redirect
This is an example Vue 3 component with a few page routes configured and a default catch all redirect to the home page.
import { createRouter, createWebHistory } from 'vue-router';
import { HomeView, AboutView, ServicesView, ContactView } from '@/views';
export const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
linkActiveClass: 'active',
routes: [
{ path: '/', component: HomeView },
{ path: '/about', component: AboutView },
{ path: '/services', component: ServicesView },
{ path: '/contact', component: ContactView },
// default redirect to home page
{ path: '/:pathMatch(.*)*', redirect: '/' }
]
});
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some Vue 3 Help?
Search fiverr to find help quickly from experienced Vue 3 developers.