How to implement a custom 404 error page in Vue.js



Image not found!!

In a Vue.js application, you can implement a custom 404 error page by creating a component for the page and configuring your router to redirect to this component when a route is not found. Here's a step-by-step guide:

  1. Create a 404 Component: Create a new Vue component that will serve as your custom 404 error page. For example, you can create a component named NotFound.vue:

    html
    <!-- NotFound.vue --> <template> <div> <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> /* Add your custom styling for the 404 page */ </style>
  2. Configure the Router: In your router configuration file (typically router/index.js), import the NotFound component and add a wildcard route that redirects to the NotFound component. The wildcard route will match any undefined route:

    javascript
    // router/index.js import Vue from 'vue'; import VueRouter from 'vue-router'; import NotFound from '@/views/NotFound.vue'; Vue.use(VueRouter); const routes = [ // Your other routes go here // Add the wildcard route for 404 { path: '*', component: NotFound } ]; const router = new VueRouter({ mode: 'history', routes }); export default router;
  3. Handle 404 in the Server Configuration (if using history mode): If you are using Vue Router's history mode, you need to configure your server to handle 404 errors by redirecting to your main index.html file. This step depends on the server you are using. For example, in the case of Apache, you might use an .htaccess file:

    apache
    <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule>

    Adjust this configuration based on your server setup.

  4. Test: Now, when a user tries to access a non-existent route, they should be redirected to your custom 404 error page.

Remember to customize the content and styling of your NotFound component based on your application's design and requirements.