如何设置vue路由器导航守卫路由到子路由而不出现无限循环?

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

我的路线有一条带有子项的父路径。如何在父路由上设置导航守卫以路由到子路由而不触发无限循环?

当我导航到“path/parent/child1”或“path/parent/child2”时,这个 beforeEnter 会循环

path: "path/parent",
beforeEnter: (to, from, next) => {
if(checkSomethingInDB) {
if(checkSomethingElseInDB){
next()
}else{
next({name: 'child1'})
} else {
next({name: 'child2})
}
}
...
vue-router
1个回答
0
投票

我最近遇到了这个问题,当尝试访问子路线时,并且在父路线中有一个导航守卫。

解决了检查我要去的路线的数学数是否等于 1 的问题,这意味着我位于路线的第一层,即父级。 如果结果大于 1 ,则意味着我要走子路线。

我还可以使用该逻辑通过子项实现特定的导航防护。

path: "/",
beforeEnter: async (to) => {
  if (to.matched.length == 1) { /* Guard only for the parent */ }
},
children: [
  { path: "/children1", },
  { 
    path: "/children2", 
    beforeEnter: async (to) => {
      if (to.matched.length == 2) { /* Guard only for this child */ }
    },
    children: [
      { path: "/children21", },
      { path: "/children22", },
    ]
  },
]
© www.soinside.com 2019 - 2024. All rights reserved.