How to open my 404 component in case of error without changing the URL in Vue.js

Asked

Viewed 194 times

0

How do I open my "Notfound" component, inside another component, using beforeRouteEnter, without changing the url?

I created a dynamic route, and a * to open "Notfound" in all other cases.

{

    path: '/work/:id',
    name: 'work',
    component: () => import( './views/Work.vue' )

},

{

    path: '*',
    name: 'NotFound',
    component: () => import( './views/NotFound.vue' )

}

Inside the Work.Vue component I check to see if the id exists in the static json. If it does not exist, call "Notfound"

beforeRouteEnter (to, from, next) {
    next(vm => {
        vm.item = json.find(item => item.id == vm.$route.params.id)

        if(!vm.item) {
            next({name: NotFound})
        }

    })
}

It calls "Notfound" (that is, the message I created in this component appears), the problem is that the url changes from site.com.br/work/id-non-existent to the root, that is www.site.com.br. I wish the url wasn’t changed.

1 answer

1

Try to use this, I believe it should work:

  {
    path: '/404',
    name: 'notFound.index',
    component: () => import( './views/NotFound.vue' ),
  },
  { path: '*', redirect: '/404' },
  • I appreciate the answer, but in case I don’t want to redirect the errors to the route /404. I would like the url with the error in the page.

  • I get it, you have two options when I see use alias or use history replaceState... I would recommend trying the alias first, I believe it should work :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.