使用 vue-router 在登录后重定向到请求的页面

在我的应用程序中,一些路由只对经过身份验证的用户可访问。< br > 当未经身份验证的用户单击一个必须为其签名的链接时,他将被重定向到登录组件。< br >
如果用户成功登录,则 我想在他登录之前将他重定向到他请求的 URL。但是,如果用户在登录之前没有请求另一个 URL,则使用 也应该有一个默认的路线。< br > < br > 如何使用 vue-router 实现这一点? < br >


我的代码没有重定向后登录

router.beforeEach(
(to, from, next) => {
if(to.matched.some(record => record.meta.forVisitors)) {
next()
} else if(to.matched.some(record => record.meta.forAuth)) {
if(!Vue.auth.isAuthenticated()) {
next({
path: '/login'
// Redirect to original path if specified
})
} else {
next()
}
} else {
next()
}
}
)



登录组件中的登录函数

login() {
var data = {
client_id: 2,
client_secret: '**************',
grant_type: 'password',
username: this.email,
password: this.password
}
// send data
this.$http.post('oauth/token', data)
.then(response => {
// authenticate the user
this.$auth.setToken(response.body.access_token,
response.body.expires_in + Date.now())
// redirect to route after successful login
this.$router.push('/')
})
}
97747 次浏览

这可以通过在路由中添加 重定向路径作为 查询参数来实现。

然后,当您登录时,您必须检查是否设置了重定向参数:

  • 如果 是的设置重定向到在 param 中找到的路径
  • 如果是 没有设置你可以回到根。

给你的链接添加一个动作,例如:

onLinkClicked() {
if(!isAuthenticated) {
// If not authenticated, add a path where to redirect after login.
this.$router.push({ name: 'login', query: { redirect: '/path' } });
}
}

登录提交操作:

submitForm() {
AuthService.login(this.credentials)
.then(() => this.$router.push(this.$route.query.redirect || '/'))
.catch(error => { /*handle errors*/ })
}

有了这个图书馆就容易多了 登入功能是

let redirect = this.$auth.redirect();
this.$auth
.login({
data: this.model,
rememberMe: true,
redirect: { name: redirect ? redirect.from.name : "homepage",  query: redirect.from.query },
fetchUser: true
})

我知道这是旧的,但它是在谷歌的第一个结果,对于那些你只是想给你这是你添加到你的两个文件。在我的情况下,我使用 Firebase 认证。

路由器

这里的关键行是 const loginpath = window.location.pathname;,在这里我得到它们第一次访问的相对路径,然后在重定向中作为查询传递下一行 next({ name: 'Login', query: { from: loginpath } });

router.beforeEach((to, from, next) => {
const currentUser = firebase.auth().currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);


if (requiresAuth && !currentUser) {
const loginpath = window.location.pathname;
next({ name: 'Login', query: { from: loginpath } });
} else if (!requiresAuth && currentUser) next('menu');
else next();
});

登入网页

这里没有魔术,你只会注意到我的动作后,用户被认证的 this.$router.replace(this.$route.query.from);,它发送他们到查询网址,我们早些时候生成。

signIn() {
firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(
(user) => {
this.$router.replace(this.$route.query.from);
},
(err) => {
this.loginerr = err.message;
},
);
},

我将更详细地充实这个逻辑,但它的工作原理是。我希望这对那些看到这一页的人有所帮助。

这个可以帮助你。

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

另一个快速而简单的方法是像下面这样使用本地存储:

  1. 在 before each 中,在重定向到登录之前,请放置以下代码行,以保存到本地存储的初始请求路径:

    路由器 JS
    //如果用户未经身份验证,则在重定向到登录之前
    localStorage.setItem('pathToLoadAfterLogin', to.path)

  2. 然后,在登录组件中,成功登录后,可以重定向到先前创建的 localStorage 变量:

    登录 Vue
    //如果用户登录成功,将它们路由到它们以前请求的路由或某个默认路由 < br > this.$router.push(localStorage.getItem('pathToLoadAfterLogin') || 'somedefaultroute');

接下来是 Matt C 的回答,这可能是最简单的解决方案,但是这篇文章有一些问题,所以我认为最好写一个完整的解决方案。

目标路由可以存储在浏览器的会话存储中,并在身份验证后检索。在这种情况下,使用会话存储比使用本地存储的好处是,在浏览器会话结束后,数据不会逗留。

在路由器的 before 每个钩子设置会话存储中的目标路径,以便它可以在身份验证后检索。如果通过第三方认证提供商(Google、 Facebook 等)进行重定向,也可以使用这种方法。

路由器 JS

//如果用户没有经过身份验证,请在重定向到 login in before each 之前进行验证

sessionStorage.setItem('redirectPath', to.path)

所以一个更完整的例子可能看起来像这样。我在这里使用 Firebase,但是如果你不是,你可以根据你的目的修改它:

router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(x => x.meta.requiresAuth);
const currentUser = firebase.auth().currentUser;


if (requiresAuth && !currentUser) {
sessionStorage.setItem('redirectPath', to.path);
next('/login');
} else if (requiresAuth && currentUser) {
next();
} else {
next();
}
});

登录 Vue

在登录方法中,经过身份验证后,将有一行代码将用户发送到不同的路由。此行现在将从会话存储中读取值。然后,我们将从会话存储中删除该项,以便将来不会意外地使用它(例如,如果您的用户在下一次身份验证时直接进入登录页面)。

this.$router.replace(sessionStorage.getItem('redirectPath') || '/defaultpath');
sessionStorage.removeItem('redirectPath');

一个更完整的例子可能是这样的:

export default Vue.extend({
name: 'Login',
data() {
return {
loginForm: {
email: '',
password: ''
}
}
},
methods: {
login() {
auth.signInWithEmailAndPassword(this.loginForm.email, this.loginForm.password).then(user => {


//Go to '/defaultpath' if no redirectPath value is set
this.$router.replace(sessionStorage.getItem('redirectPath') || '/defaultpath');


//Cleanup redirectPath
sessionStorage.removeItem('redirectPath');


}).catch(err => {
console.log(err);
});
},
},
});

这招对我很管用。

 this.axios.post('your api link', {
token: this.token,
})
.then(() => this.$router.push(this.$route.query.redirect || '/dashboard'))

如果设置了如下路线防护

router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!loggedIn) {
next({
path: "/login",
query: { redirect: to.fullPath }
});
} else {
next();
}
} else {
next();
}
});

可以提取重定向查询并在成功登录时使用它

let searchParams = new URLSearchParams(window.location.search);


if (searchParams.has("redirect")) {
this.$router.push({ path: `${searchParams.get("redirect")}` });
} else this.$router.push({ path: "/dashboard" });