To create a custom 404 error page in a Vue.js single-page application, you can follow these steps:
Create a Component for the 404 Page: First, create a Vue component for the 404 page. This component will represent the content of the custom error page.
Configure Routing: Configure your Vue Router to handle 404 errors by redirecting to the custom 404 page whenever a route is not found.
Here's a step-by-step guide:
Create a new Vue component for the 404 page. For example, you can create a file named NotFound.vue
in your src/components
directory:
html<template>
<div class="not-found">
<h1>404 Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</div>
</template>
<script>
export default {
name: 'NotFound'
}
</script>
<style scoped>
.not-found {
text-align: center;
margin-top: 50px;
}
</style>
Update your Vue Router configuration to redirect to the custom 404 page whenever a route is not found. You can do this by adding a wildcard route (*
) that matches all paths and redirects to the NotFound
component.
javascript// In your router configuration (usually in src/router/index.js)
import Vue from 'vue';
import VueRouter from 'vue-router';
import NotFound from '../components/NotFound.vue';
Vue.use(VueRouter);
const routes = [
// Your existing routes
// Add other routes as necessary
{
path: '*',
component: NotFound
}
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
});
export default router;
Now, whenever a user navigates to a route that doesn't exist within your Vue application, they will be redirected to the custom 404 page.
You can customize the NotFound.vue
component to match the look and feel of your application by adding CSS styles and additional content as needed.
With these steps, you've successfully created a custom 404 error page in your Vue.js single-page application.