如何从 Vue.js 上的 url 获取参数并在路由器文件中使用它?

How get the param from url on Vue.js and use it in router file?

我有 router 文件,其中包含我所有的路线。

这是一条路线的例子:

    path: '/events/:step',
    children: [
      {
        path: '',
        name: 'event.step',
        components: {
          default: Event,
          sidebar: EventSidebar
        }
      }
    ],
    props: {
      default: ({ params, query: { id } }) => ({ id, ...params })
    },
    components: {
      header: () => import('NavBar'),
      default: () => import('Event')
    },
    async beforeEnter(to, from, next) {
      if (step === 'login') { // can't find step
        // do something
      }
      next()
    }

我需要从路由中获取 step 参数,如果它是 loginbeforeEnter 函数中做一些事情。 我怎样才能得到它?

要从路由获取参数,你需要使用 to.paramsfrom.params,如果你想访问路径,你可以从 to.pathfrom.path 获取它取决于什么你需要。

有关 https://router.vuejs.org/api/#routelocationnormalized

的更多信息

您可以使用 router.beforeEach:

在守卫之前注册全局
router.beforeEach((to, from, next) => {
  if (['Login', 'Signup'].includes(to.name) && logged_in)
    next({ name: 'Home' })
  else next()
})

https://router.vuejs.org/guide/advanced/navigation-guards.html