如何在 Vue.js 3 中使用 vue 路由器将 404 路由重定向到主页

How to redirect a 404 route to Home using vue router in Vue.js 3

你好全能社区!

我有一个小问题Vue.js 3.在路由器中,我无法定义任何未知路由应该重定向到“/”。

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
 {
    path: "/*",
    redirect: "/",
  }
]

在这里,我测试了 redirect: "/" 有效,但 path: "/*" 无效。路径 "/" 仅适用于 domain.com/... 我也测试了 path: "*" 但我收到此错误:

"Uncaught Error: Route "" should be "/"."

最新的 Vue.js3 中如何进行 404 重定向?

在与 Vue 3 兼容的 Vue 路由器 4 中,您可以 Catch all / 404 Not found Route 如下:

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: "/",
  }
]

LIVE DEMO