在 Vue 和 Vue Router SPA 中,未找到资源显示 404

har*_*ryg 4 javascript single-page-application vue.js vue-router

我在 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 }
})
Run Code Online (Sandbox Code Playgroud)

在我的工作中,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)
  })
}
Run Code Online (Sandbox Code Playgroud)

本质上,它可能涉及用 替换FooShowPage路由器视图中的NotFoundPage,或重定向到定义的 404 页面,同时保持浏览器历史记录不变。

Leo*_*Leo 6

您需要为 404 页面设置路由,然后将不匹配的路由重定向到它。我用一个router.redirect后图来做这样的事情。

router.map({
  '/': { name: 'home', component: HomePage },
  '/foo/:id': {name: 'foo-show', component: FooShowPage},
  '/404': {name: 'not-found', component: NotFound}
})

router.redirect({
    '*': '/404'
})
Run Code Online (Sandbox Code Playgroud)

地图中未列出的所有路线将被重定向到 /404