Vue路由器-捕获所有通配符不起作用

问题描述

我正在将Vue Router与Vue 3配合使用,并试图添加一个包罗万象的路由来重定向用户(如果他们尝试访问无效的URL)。尝试使用通配符(*)时,出现以下错误记录到控制台:

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)

我假设这是因为我没有在包含星号的路径前添加'/',但是如果执行此操作,则catch全部无效。这是我的路线:

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

通配符路由是路由数组中的最后一个对象。有人知道我在做什么错吗?

解决方法

使用带有自定义正则表达式的参数捕获所有路由(/ *)must now be defined/:catchAll(.*)

例如:

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

对于Vue 2中的Vue 2的*(加星标或包含全部),我个人使用:

{
  path: '/:pathMatch(.*)*',<== THIS
  name: 'not-found',component: NotFound
}

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

参数名称可以是catchAll,pathMatch,noPage等类似的任意名称

{
  path: '/:pathMatch(.*)*',//will match everything and put it under `$route.params.pathMatch`
  name: 'not-found',component: NotFound
}
{ 
  path: '/user-:afterUser(.*)',// will match anything starting with `/user-` and put it under `$route.params.afterUser`
  component: UserGeneric
}


/:pathMatch(.*)*

  • 如果您打算使用其名称直接导航到未找到的路线,则最后一个*是必要的。

  • 如果在参数中省略了/字符,则在解析或推送时将对其进行编码。

例如,如果您使用path: /:pathMatch(.*)(注意:没有最后一个星号),然后转到/user/not-found(一个不存在的页面),则this.$route.params.pathMatch将是一个字符串= > 'user/not-found'

// bad example if using named routes:
router.resolve({
  name: 'bad-not-found',params: { pathMatch: 'not/found' },}).href // '/not%2Ffound'

相反,如果您使用path: /:pathMatch(.*)*(请注意:带有星号),this.$route.params.pathMatch将是一个数组['user','not-found']

// good example:
router.resolve({
  name: 'not-found',params: { pathMatch: ['not','found'] },}).href // '/not/found'

请阅读文档:From migration from vue 2 to vue 3Catch all / 404 Not found Route

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...