vue.js(v3)使用错误组件而不更改URL
我已经搜索和修补了一段时间,没有任何运气。我希望能够捕获错误并显示一个“糟糕”页面。需要明确的是,这不是大约404页(正常工作)。
为了简单起见,我已经减少了这一点,但是在下面的页面加载之前,它“尝试可能失败的东西”。失败后,我导航到/error
显示错误页面:
const router = createRouter({
routes: [
{
path: '/',
component: Index
},
{
path: '/something',
component: Something
},
{
path: '/error',
component: Error
},
{
path: '/:catchAll(.*)',
component: NotFound
}
]
})
router.beforeEach(async (to, from, next) => {
// attempt something which may fail
})
router.onError(() => router.push('/error'))
这一切都很好,但这意味着/error
路径是可导航的,并且路径更改发生。我希望的是,如果发生错误,则可以显示错误组件(错误
)的方法。
假设我在/
上,然后我导航到/sosings
,但是“某物失败”,URL路径将等于,但是
错误
组件将被使用,而不是某物
组件。
有什么想法吗?看来这应该是可以管理的,但是到目前为止,我已经空白了。
谢谢
I've been searching and tinkering for a while now without any luck. I'm looking to be able to catch errors and show an "Oops" page. Just to be clear, this isn't about 404 pages (which work fine).
I've reduced this for simplicity but in the below, before a page loads, it "attempts something which may fail". When that fails, I navigate to /error
which shows an error page:
const router = createRouter({
routes: [
{
path: '/',
component: Index
},
{
path: '/something',
component: Something
},
{
path: '/error',
component: Error
},
{
path: '/:catchAll(.*)',
component: NotFound
}
]
})
router.beforeEach(async (to, from, next) => {
// attempt something which may fail
})
router.onError(() => router.push('/error'))
This all works fine, but it means that the /error
path is navigable, and that a path change occurs. What I'd prefer is a way to be able to show an error component (Error
) if an error occurs while keeping the url path the same.
Say I was on /
and then I navigated to /something
but "something failed", the url path would equal /something
but the Error
component would be used, rather than the Something
component.
Any ideas? It seems like this should be manageable but so far I'm coming up blank.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AS duannx 上面评论,解决方案是使用状态来控制这一点。以下是我这样做的方法:
我创建了一个PINIA商店来容纳一个错误变量:
在路由器中,我捕获任何错误:
在root组件(
app.vue
)中,然后检查错误状态。 ,并根据是否设置错误状态来显示该视图或路由器视图。这很好,谢谢Duannx。
As Duannx commented above, a solution to this was to use a state to control this. Here's how I did it:
I created a Pinia store to hold an error variable:
In the router, I catch any errors:
In the root component (
App.vue
), I then check for the error state, and either show that or the router view based on whether or not the error state is set the true.This works great, thanks Duannx.