VueJS 通过路由器 next() 传递参数

Joh*_*ohn 6 parameters vue.js vue-router vuejs2

当我在 /login 中时,我想将最后一条路由传递到我的路由器中,以便在登录到所需路由时重定向用户。

所以用户转到/payment我重定向到/login,当身份验证正常时,我想将用户重定向到payement

这是我的 router.js :

import ...

Vue.use(Router)

let router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/about',
      name: 'about',
      component: About
    },
    {
      path: '/payment',
      name: 'payment',
      component: Payment,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/my-account',
      name: 'my-account',
      component: MyAccount,
      meta: {
        requiresAuth: true
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  console.log('Before Each Routes')
  if(to.matched.some(record => record.meta.requiresAuth)) {
    if (store.getters.isLoggedIn) {
      console.log('Logged in')
      next()
      return
    }
    console.log(to.fullPath)
    next({
      path: '/login',
      params: { nextUrl: to.fullPath }
    })
    return
  } else {
    console.log(to.fullPath)
    next()
  }
})

export default router
Run Code Online (Sandbox Code Playgroud)

所以我设置了一些 console.log ,我得到了这个:

如果我直接进入 /login,输出:

Before Each Routes
/login
Run Code Online (Sandbox Code Playgroud)

然后,如果我转到 /payment,输出:

Before Each Routes
/payment
Before Each Routes
/login
Run Code Online (Sandbox Code Playgroud)

所以现在当我进入我的登录组件并使用this.$route.params.nextUrl它时,它是未定义的。该next()参数不存在,我不知道为什么。

我做错了什么?

Tri*_*ton 9

看起来您混淆了两种不同的机制:参数和查询。参数必须是 url 的一部分,就像/user/:id查询参数是自动附加的一样。

你要这个:

next({
    path: '/login',
    query: {
       nextUrl: to.fullPath,
    }
})
Run Code Online (Sandbox Code Playgroud)

相关阅读:https : //router.vuejs.org/api/#route-object-properties


oma*_*ari 6

当将 url 作为参数传递时,Tristan 的上述方法是最好的。但是,在正常情况下,我们会传递类似 id 的内容,因此您可以使用它:

next({ name: 'account', params: { id: 3 } });
Run Code Online (Sandbox Code Playgroud)

添加替换选项以防止导航出现在历史记录中:

next({ name: 'account', params: { id: 3 }, replace: true });
Run Code Online (Sandbox Code Playgroud)

我正在使用 vue-router 3.1.6。