1

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?

2
  • try use vue-router guards Commented Aug 22, 2020 at 16:26
  • I'd say it is not a good practice to do what you're trying to do in the mutation there are navigation guards you can use. Commented Aug 22, 2020 at 16:37

1 Answer 1

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") 
}
Sign up to request clarification or add additional context in comments.

1 Comment

you should to use vue-router guards like a middleware before to join to some route, there you can apply the corresponding logic. also inside your component you can use the beforeRouteEnter guard as a secondary option

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.