One way to handle routing to a page outside of a Vue app is to use a basic route handler and redirect from there. Here’s an example:
const routes: [
// applications all routes
{ path: '/', component: () => import('./components/HomeComponent') },
{ path: '/admin', component: () => import('./components/AdminComponent') },
{ path: '/user', component: () => import('./components/UserComponent') },
// the default route, this runs when none of the above routes matches
{ path: '*', component: () => import('./components/PageNotFound') }
]
const router = new VueRouter({
mode: 'history',
routes
})
Now, in the PageNotFound Component, one can specify the actual redirect that will take the user out of the app entirely:
<script>
export default {
name: 'PageNotFound',
created() {
window.location.href = '/404.html'
},
}
</script>
> Please note that one can use either the created or mounted hook to perform the redirect. It will work for both.
> Also, note that it needs to build a production version of the app to ensure the redirect happens. Additionally, testing this in Vue-CLI won’t work as it requires server-side handling.
> In single-page apps, the server usually sends out the same index.html and app scripts for all route requests. This won’t work for the 404.html unless the server treats it as a special case and serves the static page.
In the case of the latest version, Vue 3 or later, the ‘* (asterisk)’ path property needs to be replaced with ‘/:pathMatch(.*)*’, as the old catch-all path is no longer supported. The reason is that the Vue Router no longer relies on ‘path-to-regexp’ and has instead implemented its own parsing system. This system is the common practice to include a single catch-all route in most projects, there is no substantial benefit in supporting a specialized syntax for the wildcard character “*”. Additionally, to maintain predictability and consistency, the encoding of parameters remains the same across all routes.
Here’s an example of it:
{ path: '/:pathMatch(.*)*', component: () =>
import('./components/PageNotFound') }
Work with our skilled Vue developers to accelerate your project and boost its performance.
Hire Vuejs Developers