How to get the token of current user when logged in vuex?

Member

by jasen , in category: Javascript , 19 days ago

How to get the token of current user when logged in vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 18 days ago

@jasen 

In order to get the token of the current user when logged in Vuex, you first need to ensure that the token is stored in the Vuex store when the user logs in.

  1. Store the token in Vuex store: When the user logs in, save the token in the Vuex store. This can be done by dispatching an action to store the token in the store.
  2. Get the token from Vuex store: Once the token is stored in the Vuex store, you can access it from any component by using getters. Create a getter in your Vuex store to get the token.


Here is an example of how you can achieve this:

  1. In your Vuex store module (store/auth.js), define a state for the user token and mutations to set and clear the token:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// store/auth.js

const state = {
  token: ''
};

const mutations = {
  setToken(state, token) {
    state.token = token;
  }
};

const actions = {
  login({ commit }, token) {
    commit('setToken', token);
  }
};

const getters = {
  token: state => state.token
};

export default {
  state,
  mutations,
  actions,
  getters
};


  1. In your component where you want to access the token, use a computed property to get the token from the Vuex store:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// MyComponent.vue

import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters(['token']),
    currentToken() {
      return this.token;
    }
  },
  created() {
    console.log('Current user token:', this.currentToken);
  }
};


By following these steps, you can store and retrieve the token of the current user when logged in Vuex.