NuxtJS redirect after login

2020-07-13 08:20发布

问题:

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')
}

and 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
}

回答1:

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).

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



回答2:

.
.
.


        data: () => ({

          previousPage:null,

        }),
        beforeRouteEnter(to, from, next) {
          next(vm => {
            vm.previousPage = from
          })
        },
    created(){
       console.log(this.previousPage.name);
    }
.
.
.

Try this