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: '/' } ] });
Need Some Vue 3 Help?
Search fiverr for freelance Vue 3 developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!