使用 vue-router 来包罗万象/保留原始 url 和 SPA

问题描述 投票:0回答:1

我很难让 vue-router 访问:

  • 保留用户输入的原始无效网址
  • 显示嵌入的 404 页面

从文档/示例中我看到我似乎能够做到其中之一,但不能同时做到两者。例如,下面的代码将正确嵌入 404 页面,但 URL 将更改为 /subpage/404,而不是用户最初输入的内容。我尝试过(不成功)使用别名,因为我不知道用户是什么输入无效。也许我用错了或者用在了错误的地方?

根据下面的示例代码,这可以完成吗?

const routes = [{ 
  path: '/', 
  redirect { path: '/subpage' }, 
  children: [{
    path: '/subpage',
    component: () => import ('SubPage.vue'),
    children: [{
      path: '404',
      name: '404',
      component: () => import('NotFound.vue')
    }] // Omitted other children for this example
  }]
}, {
    path: '/:pathMatch(.*)*', 
    redirect: { path: 'subpage/404' }
}];
vue-router vue-router4
1个回答
0
投票

/:pathMatch(.*)*
是一个包罗万象的路径,这意味着任何不匹配其上方 any 路由的路径将始终与此路由匹配,您可以使用它来显示 404 组件。它甚至会覆盖无效的子路径,例如
/subpage/invalidpath
,所以只需使用 catch-all 路径来显示实际的 404 组件,而不是重定向。

const routes = [
  {
    path: '/',
    redirect: { path: '/subpage' },
    children: [
      {
        path: '/subpage',
        component: () => import('SubPage.vue'),
        children: [
          // 404 component not needed here
        ]
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => import('NotFound.vue')
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.