如何使用vue-router中间件将用户重定向回他来自的页面?

时间:2017-07-07 04:04:53

标签: node.js vuejs2 vue-router

我有以下代码创建了以下代码,作为我的vue组件的中间件。

  Router.beforeEach(
  (to, from, next) => {
    if (to.matched.some(record => record.meta.forVisitors)) {
      if (Vue.auth.isAuthenticated()) {
        next({
          path: '/home'
        })
      } else next()
    } else if (to.matched.some(record => record.meta.forAuth)) {
      if (!Vue.auth.isAuthenticated()) {
        next({
          path: '/login'
        })
      } else next()
    } else if (to.matched.some(record => record.meta.forLog)) {
      if (Vue.auth.isAuthenticated()) {
        next({
          path: from()
        })
      }else if (!localStorage.getItem('validUser')) {
                next({
          path: '/login'
        })
            } else next()
    } else next()
  }
)

大多数中间件工作正常。但from()无效。 我也尝试将此作为from,但它仍然没有将用户重定向回他来自的页面。

1 个答案:

答案 0 :(得分:0)

如果你console.log from,你会得到以下

Object {name: null, meta: Object, path: "/", hash: "", query: Object…}
fullPath
:
"/"
hash
:
""
matched
:
Array(0)
meta
:
Object
name
:
null
params
:
Object
path
:
"/"
query
:
Object
__proto__
:
Object

您可以看到from不是string而是对象。相反,请使用对象的path属性,如下面的示例

else if (to.matched.some(record => record.meta.forLog)) {
   if (Vue.auth.isAuthenticated()) {
    console.log(from);
    next({
       path: from.path
    })
相关问题