Data Mastery
Data Mastery

Reputation: 2095

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?

Upvotes: 1

Views: 639

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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

Upvotes: 1

Related Questions