如何将用户重定向回他使用 vue-router 中间件的页面?
How do I redirect the user back to the page he comes from using vue-router middleware?
我创建了以下代码作为我的 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
但它仍然没有将用户重定向回他来自的页面。
如果你 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
})
我创建了以下代码作为我的 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
但它仍然没有将用户重定向回他来自的页面。
如果你 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
})