Home » vue » How to load component for not existing route? 404 component for vue + webpack

How to load component for not existing route? 404 component for vue + webpack

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have defined my routes like this:

const routes=[
{
    path:'/',
    component:Home,
}, ...

I would like to show a vue webpack component when the visitor goes to a route that it is not defined in my routes settings
How canI do it? I mean, show a vue webpack component as a 404 error page?
Thanks

Answers:

Use a catch all route at the end of your list of routes.

const routes = [
  {
      path:'/',
      component:Home,
  },
  {
      path: "*",
      component: NotFound
  }
]

Here is an example.

console.clear()

const Foo = { template: '<div>foo</div>' }
const NotFound = { template: '<div>404 page</div>' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '*', component: NotFound }
]

const router = new VueRouter({
  routes 
})

const app = new Vue({
  router
}).$mount('#app')
<script src="https://unpkg.com/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/2.7.0/vue-router.js"></script>

<div id="app">
  <router-view></router-view>
</div>