How to access this.$router in actions

Hi,

i cant redirect a router from vuex actions

this.$router is undefined

axios.post(api_url, queryString.stringify(payload),{
  headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
}).then((response) => {
    console.log(response.data)

    if(response.data.error){
      commit('setLogginError', true)
    }
    else{
      commit('setUser', response.data)
      this.$router.push('/team')
    }


}).catch(function (error) {
    console.log(error);
});

你可以在data中申明一个变量,默认为false.在判断中让它为true,然后用watch监听它的状态。在监听中判断,它为true的时候,进行路由跳转。

这可能绕了很大的一个圈子,但是效果应该是有的

Can you write this in English ?

You can declare a variable in data, default to false. Make it true in your judgment, and then monitor its state with watch. In listening, when it is true, it will be routed.

1 Like

This may have been a big circle, but the effect should be there

This is translated by translation software… I can’t speak English

I guess @plfqz did not understand the question.

What keeps you from simply importing the router?

2 Likes

I think maybe (this) has changed…

You can define another this instance before axios call

I have passed the global router through action payload

  this.$store.dispatch('authenticate' , {
            email : this.email.trim(),
            password : this.password.trim(),
            router : this.$router
          })

and then used it in the action like this

let router = payload.router

solved :slight_smile: .

1 Like

Maybe you souldn’t redirect in vuex. That has nothing to do with the app state.

3 Likes

If you are going to do route changes in Vuex I think it would be simpler to import the router in your store or Vuex module.

import router from '../router/index.js';

1 Like

u can use

import router from '@/router'

and use

router.push('/)
4 Likes

You can’t implement router push in the vuex action. Calling vuex action will return a Promise. Therefore, try this.

in vuex

SampleAction({commit}){};

in your component

methods:
{
…mapActions([‘SampleAction’]),
Sample(){
this.SampleAction()
.then((e) => {
this.$router.push(’/’);
})
.catch((e) => {});
}
}

Well it works