【发布时间】:2016-11-17 12:21:53
【问题描述】:
我在 SPA 中使用 Vue 和 Vue Router。在视图组件中,我在资源库中查询资源。如果找不到资源,我想在保留 URL 的同时显示 404 页面。
即如果我访问/foo/non-existant-id,那么应该显示一个 404 页面来代替 foo 资源的显示页面。
为了清楚起见,这里是我的路由器地图:
router.map({
'/foo/:id': {name: 'foo-show', component: FooShowPage},
// Utilities
'/': { name: 'home', component: HomePage },
'*': { name: '404', component: NotFoundPage }
})
在我的FooShowPage 中,我执行以下操作:
ready () {
// fetch the foo from the repo (app.foos)
app.foos.fetchById(this.$route.params.id).then(foo => {
this.foo = foo
}).catch(e => {
// foo is not found show a 404 page
// using this.$route.router.go({name: '404'}) does not work as route is a wildcard
console.warn(e)
})
}
基本上它可能涉及用NotFoundPage 替换路由器视图中的FooShowPage,或者重定向到定义的404 页面,同时保持浏览器历史记录不变。
【问题讨论】:
-
你解决了吗?我目前正在调查这个问题,提供的答案对我不起作用,因为在我从后端 API 检索结果之前我不知道哪个 id 有效
-
我有同样的问题,但在任何地方都找不到解决方案。在我进行 api 调用并收到 404 之前,我不知道动态参数是否有效。
标签: javascript single-page-application vue.js vue-router