Search code examples
vue.jsvuexvue-routervue-props

Passing OAuth token from one Vuejs component to another


I get OAuth token after successful OAuth login in a SuccessOAuth.vue component. I get the token details as follows:

           checkforTokens(){
             const queryString = this.$route.query;
             console.log(queryString);
             const token = this.$route.query.accessToken
             console.log(token);
             const secret = this.$route.query.tokenSecret
             console.log(secret);
             this.tokens.token = token;
             this.tokens.secret = secret;
          }
       },
       beforeMount() {
           this.checkforTokens();
       }

Now I want to use this token in another component apiCalls.vue where I use this token details to use call the API methods.

<script>
...
 methods:{

      getProductDetails() {
      console.log("==========================================");
      console.log(".. Get Product details....");
      axios
        .get("/auth/getShpDetails", {
          params: {
            token: this.tokens.token
          }
        })
        .then(response => {
          const productInfo = response.data;
          console.log("Product info :" + productInfo);
        });
    },

}
</script>

How do I pass the token details from SuccessOAuth component to apiCalls. I tried using props method but I wasn't able to get the token value to the script tag, not sure about other methods used to pass i.e using $emit and using vuex. Please suggest the best way and the right solution for the problem.


Solution

  • As suggested by @Nishant Sham, I am just modifying the action method in index.js as seen below:

    import Vue from 'vue'
    import Vuex from "vuex";
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
        state: {
              token: ''
        },
        getters: {
          getToken(state){
            return state.token;
          }
        },
        mutations: {
            setToken(state, tokenValue){
              state.token = tokenValue;
            }
        },
        actions: {
          setToken({commit}, tokenValue){
            commit("setToken", tokenValue);
          }
        }
       });
    

    In your vue component you call getters and setters as follows:

    <script>
          //Set token value
          var token = "dwe123313e12";//random token value assigned
          this.$store.commit("setToken", token);
    
          .....
    
          //Get token value
          var getToken = this.$store.getters.getToken;
    </script>