登录后 NuxtJS 重定向 [英] NuxtJS redirect after login
问题描述
我正在使用 nuxtjs 和 Laravel Passport.如果用户转到/someurl,但登录方法推送到 '/' 我如何将/someurl 存储在会话中,以便在登录时可以推送到会话变量?我有一个被调用的会话变量,但它在身份验证中间件中被刷新.我显然错过了一些东西.这是我的代码:在 auth.js
中间件文件
I'm using nuxtjs and Laravel Passport. If a user goes to /someurl, but the login method pushes to '/' how do I store /someurl in the session so that I can push to the session variable when logging in? I have a session variable that is called, but it get's refreshed in the authentication middleware.
I'm clearly missing something.
Here is my code: in auth.js
middleware file
export default function ({ route, store, redirect }) {
let params = ''
if (!route.path.startsWith('/login') && !route.path.startsWith('/assets') && route.path !== '/') {
store.state.requestUrl = route.path
}
if (!store.state.authenticated) {
return redirect('/login')
}
并登录
await this.$store.dispatch('login', {
username: this.loginDetails.username,
password: this.loginDetails.password
})
this.$router.push(this.$store.state.requestUrl) // this is always '/'
} catch (e) {
console.log(e)
this.failedLogin = true
}
推荐答案
您需要使用mutation(store中的dispatch
方法 - 您已经在其中使用它)更改状态(store.state.requestUrl)this.$store.dispatch('login')
).所以你需要编写一个改变商店中状态的突变,例如.this.$store.dispatch('set_request_url', requestUrl)
.
You need to change a state (store.state.requestUrl) using mutation (dispatch
method in store - you used it already in this.$store.dispatch('login')
). So you need to write a mutation changing a state in the store, eg. this.$store.dispatch('set_request_url', requestUrl)
.
顺便说一句:Nuxt 中有一个用于身份验证的模块 :) https://auth.nuxtjs.org/一>我推荐使用它!但是如果我想自己实现它,我会将重定向 url 存储在 cookie 中(因为它比 vuex 更耐用).Nuxt 有一个用于存储 cookie 的模块:https://www.npmjs.com/package/cookie-universal-nuxt,但您也可以使用 vuejs cookie 模块:https://github.com/alfhen/vue-cookie
BTW: There is a module for authentication in Nuxt :) https://auth.nuxtjs.org/ I recommend to use it! But if I wanted to implement it by my own I would store a redirect url in cookies (cause it is more durable than vuex). Nuxt has a module for storing in cookies: https://www.npmjs.com/package/cookie-universal-nuxt, but you can also use a vuejs cookies module: https://github.com/alfhen/vue-cookie
这篇关于登录后 NuxtJS 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!