How to set up a 404 page in VueJS?

Hi Friends šŸ‘‹,

Welcome To SortoutCode! ā¤ļø

Today, I am going to show you How do you set up a 404 page in vueJS.

Sometimes users enter the wrong URL, instead of showing a blank page, we can show a 404 page. So, letā€™s start and set up the 404 page.

Table of Content

  • Setup the Vue (Optional)
  • Install the Vue Router
  • Create the Components for 404 Page
  • Setup the Routes for 404 Page

This article will guide you to how do I define the Not Found page for not valid URL in vueJS.

Step 1: Setup the Vue (Optional)

First, we have to install the Vue project, I had installed the vueJS in my system. If you havenā€™t installed or have any problem with installation you can follow this article, it will show you step by step process of installation. How to Install the VueJS project?

Step 2: Install the Vue Router

First Install the Vue router in the Vue project. For that, I am using this Command npm I vue-router

After the installation import the vue-router into my ā€˜router/index.jsā€™ file

import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
    routes: [{
        // ...here your componanets, path and name
    }, ],
    mode: 'history'
})
export default router

Step 3: Create the Components for 404 Page

First, letā€™s set up the 404 component.My 404 Component name is NotFound.vue, Using the <center></center> tag in template we center the heading <h1>404 not found</h1><h2>it seems you're in the wrong page</h2>.In export default set the name of Components that is NotFound.

NotFound.vue

<template>
  <div>
    <center>
      <h1>404 not found</h1>
      <h2>it seems you're in the wrong page</h2>
    </center>
  </div>
</template>
<script>
export default {
  name: "NotFound",
};
</script>

Step 4: Setup the Routes for 404 Page

Now we have to define the router,

import Vue from "vue";
import Router from "vue-router";

import NotFound from "../components/NotFound.vue";

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: "*",
      component: NotFound,
      name: "NotFound",
    },
  ],
});

when we set up the path for NotFound.vue we have to just add the * in the path, if the URL does not match with another path it will render the NotFound.vue component.

For now, letā€™s check the output.

Output

Not Found

All the best šŸ‘.

Follow me on Twitter