Search code examples
vue.jsvuejs2vue-componentvuexvue-router

Vue.js - control the router from inside a mutation in Vuex Store


I have the following problem:

This is one of my mutations:

tryAutoLogin(state) {
  console.log("Trying auto login...");
  const token = window.localStorage.getItem("token");
  if (!token) {
    return;
  }
  const expirationDate = window.localStorage.getItem("token_exp");
  const now = new Date();
  if (now >= expirationDate) {
    return;
  }
  state.userData.loggedIn = true;
  state.userData.username = token.identity;
  // desired: this.$router.push("/dashboard") => results in undefined
}

Currently I commit this mutation inside my component in the created phase of the component:

  created() {
    this.$store.commit("tryAutoLogin");
    this.$router.push("/dashboard");
  }

This is not a great way to do it, since I would have to output a value, store it in a variable and use if/else to this this.$router.push("/dashboard").

How can I solve this in an elegant way? Favorable inside the mutation like in the // desired comment. Is there a way to access the router inside the Vuex store?


Solution

  • Pass the vue component instance to the mutation like:

     this.$store.commit("tryAutoLogin",this);
     
    

    in mutation add it as parameter vm then use it as vm.$router.push("/dashboard") :

    tryAutoLogin(state,vm) {
      console.log("Trying auto login...");
      const token = window.localStorage.getItem("token");
      if (!token) {
        return;
      }
      const expirationDate = window.localStorage.getItem("token_exp");
      const now = new Date();
      if (now >= expirationDate) {
        return;
      }
      state.userData.loggedIn = true;
      state.userData.username = token.identity;
      vm.$router.push("/dashboard") 
    }