Question
使用 Vue.js,如何在不更改 url 的情况下在动态路由中返回 404 错误?
Part of my route.js (everything ok)
{
path: '/work/:id',
name: 'work',
component: () => import( './views/Work.vue' )
},
{
path: '*',
name: 'NotFound',
component: () => import( './views/NotFound.vue' )
}
Part of Work.vue component. Where i check if route param are in my static json, if not, open NotFound component before route enter
beforeRouteEnter (to, from, next) {
next(vm => {
vm.item = json.find(item => item.id == vm.$route.params.id)
if(!vm.item) {
next({name: NotFound})
}
})
}
The problem
当我尝试 site.com/work/non-existent-id 时,组件“NotFound”打开,但 url 来自 site.com/work/non-existent- id 到 site.com
What I espect
site.com/work/non-existent-id 打开组件“NotFound”并且 url 保持在 site.com/work/non-existent-id
Example
https://v2.vuejs.org/v2/guide/something - 返回 404 错误并留在 url 中
最佳答案
路由器被设计成完全按照您的意愿行事。如果您想在应用程序的任何路由上显示一些内容,我建议您创建一个新组件,并可能触发一个事件来显示您想要的任何内容。
就个人而言,我认为重新路由是可行的方法,因为这将允许用户点击浏览器中的后退按钮返回到他们来自的地方,但我想这一切都取决于您的具体用途这里的案例。
关于javascript - 如何在不更改 Vue 中的 url 的情况下返回 404 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55173218/