Vue Router - 捕获所有通配符不起作用 [英] Vue Router - catch all wildcard not working

查看:149
本文介绍了Vue Router - 捕获所有通配符不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Vue Router 与 Vue 3 一起使用,并尝试添加一个包罗万象的路由以在用户尝试访问无效 URL 时重定向用户.当我尝试使用通配符 (*) 时,我将以下错误记录到控制台:

I'm using Vue Router with Vue 3 and am trying to add a catch-all route to redirect the user if they try and access an invalid URL. When I try and use the wildcard (*), i get the following error logged to the console:

Uncaught Error: A non-empty path must start with "/"
    at tokenizePath (vue-router.esm.js?8c4f:975)
    at createRouteRecordMatcher (vue-router.esm.js?8c4f:1106)
    at addRoute (vue-router.esm.js?8c4f:1190)
    at eval (vue-router.esm.js?8c4f:1335)
    at Array.forEach (<anonymous>)
    at createRouterMatcher (vue-router.esm.js?8c4f:1335)
    at createRouter (vue-router.esm.js?8c4f:2064)
    at eval (index.js?a18c:26)
    at Module../src/router/index.js (app.js:1402)
    at __webpack_require__ (app.js:854)

我假设这是因为我没有在包含星号的路径前面加上/",但是如果我这样做,那么捕获全部不起作用.这是我的路线:

I'm assuming this is because I don't prepend the path containing the asterisk with a '/', but if I do this then the catch all doesn't work. Here are my routes:

imports...

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/user',
    name: 'User',
    // route level code-splitting
    // this generates a separate chunk (user.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "user" */ '../views/user/User.vue'),
    children: [{path: '', component: UserStart}, {path: ':id', component: UserDetail}, {path: ':id/edit', component: UserEdit, name: 'userEdit'}]
  },
  {path: '/redirect-me', redirect: '/user'},
  {path: '*', redirect: '/'}
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

export default router

通配符路由是路由数组中的最后一个对象.有谁知道我做错了什么?

The wildcard route is the last object in the routes array. Does anyone know what I'm doing wrong?

推荐答案

捕获所有路由 (/*) 现在必须使用带有自定义正则表达式的参数来定义:/:catchAll(.*)

Catch all routes (/*) must now be defined using a parameter with a custom regex: /:catchAll(.*)

例如:

    {
      // path: "*",
      path: "/:catchAll(.*)",
      name: "NotFound",
      component: PageNotFound,
      meta: {
        requiresAuth: false
      }
    }

这篇关于Vue Router - 捕获所有通配符不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆