In this article, we will look at how to implement a catch-all route to handle the page not found error and display a custom 404 page in the Vue application.
In the router configuration, we can specify a path /:notFound
and also define a NotFound
component to display the 404 custom page.
const router = createRouter({
history: createWebHistory(),
routes: [
{
// ...
},
{
path: "/:notFound",
component: NotFound,
},
],
});
The /:notFound
will match any string in the URL and display the NotFound
component. Let’s implement it and see it in action.
We will begin by creating a new application using Vue CLI.
❯ vue create catch-all-demo
Once, the installation is complete, we can navigate to the folder and run the server to load the application.
❯ cd catch-all-demo
❯ npm run serve
This will run our server on port 8080 by default http://localhost:8080/
Next, we will install the vue-router
package required for routing. We can install it using CDN, npm or yarn.
npm:
npm install vue-router@4
yarn:
yarn add vue-router@4
Once the package is installed, we can integrate it with our Vue application.
Let’s create two components for our demo purpose.
❯ touch src/components/MyComponent.vue
❯ touch src/components/NotFound.vue
We will open the files and add some template code.
<!-- MyComponent.vue -->
<template>
<h2>MyComponent</h2>
</template>
NotFound.vue
<!-- NotFound.vue -->
<template>
<h2>404 Not found. The page you are looking for does not exist.</h2>
</template>
In the main.js
we can define two routes, one route will be to display the MyComponent
and the second route will be the catch-all route which will display the NotFound
component.
// main.js
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import MyComponent from "./components/MyComponent";
import NotFound from "./components/NotFound";
const app = createApp(App);
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/my-component",
component: MyComponent,
},
{
path: "/:notFound",
component: NotFound,
},
],
});
app.use(router);
app.mount("#app");
Here, we have defined the catch-all route /:notFound
which will catch any string that does not match the predefined route paths and display the NotFound
component.
In the App.vue
let’s add the router view.
<!-- App.vue -->
<template>
<router-view></router-view>
</template>
<script>
export default {
name: "App",
};
</script>
With this let’s open up the URL http://localhost:8080/my-component
As expected, the Mycomponent
component gets displayed. Now let’s try to add some random path in the URL like http://localhost:8080/xxx or http://localhost:8080/something
As you can see, our catch route is working and is able to display the custom 404 content.