简体   繁体   中英

vue-authenticate and router redirect

I use vue-authenticate ( https://github.com/dgrubelic/vue-authenticate ) to login with ID/Password and Oauth 1 & 2.

Where I put the router redirect to redirect user on dashboard page?

this.$router.push({name: 'dashboard'})

My code store.js with Vuex:

import Vue from 'vue'
import Vuex from 'vuex'
import {vueAuth} from './auth'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isAuthenticated: false
  },
  getters: {
    isAuthenticated () {
      return vueAuth.isAuthenticated()
    }
  },
  mutations: {
    isAuthenticated (state, payload) {
      state.isAuthenticated = payload.isAuthenticated
    },
    setProfile (state, payload) {
      state.profile = payload.profile
    }
  },
  actions: {
    login (context, payload) {
      payload = payload || {}
      return vueAuth.login(payload.user, payload.requestOptions).then((response) => {
        context.commit('isAuthenticated', {
          isAuthenticated: vueAuth.isAuthenticated()
        })
      })
    }
  }
})

You can use .then() after you dispatch your action in your vue component, you can put $router.push() method after your dispatch action completed.

// SomeComponent.vue
.
.
.
methods: {
  login () {
    this.$store.dispatch('login', payload)
      .then(() => {
        this.$router.push({ name: 'dashboard' })
      })
  }
}

Or you can use in your actions.js file but I'm doing $router jobs in vue

// actions.js
import Vue from 'vue'

const actions = {
  login (context, payload) {
    payload = payload || {}
    return vueAuth.login(payload.user, payload.requestOptions)
      .then((response) => {
        context.commit('isAuthenticated', {
        isAuthenticated: vueAuth.isAuthenticated()
        Vue.$router.push({ name: 'dashboard' })
      })
    })
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM