0

i need to use $router.push in Vue-router. Check my code:

axios.interceptors.response.use(function (response) {
    return response
  }, function (error) {
    if(error && error.message === 'Network Error'){
        //here is problem. I can;t use this.$router in js file? How to fix this?
        this.$router.push('calendar')
    }
    return Promise.reject(error)
  })

My question is how do I use $router.push in this file? Check my router:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import axios from 'axios'
Vue.use(VueRouter);

axios.interceptors.response.use(function(response) {
  return response
}, function(error) {
  if (error && error.message === 'Network Error') {
    Vue.push('home')
  }
  return Promise.reject(error)
})

const routes = [{
  path: '/',
  name: 'home',
  component: Home
}, {
  other routes
}]

1 Answer 1

3

You can do this with route navigation guards.

Here's a contrived example using beforeEach (runs before every route):

router.beforeEach(async (to, from, next) => {
  const response = await axios.get(...);
  if (response.data.isGood) {
    next();
  } else {
    next({ name: 'home' });
  }
});

This would run an async call before navigating to each route, and then check the response data. If everything is good, the navigation proceeds. Otherwise, the user is redirected back to the home route.

You can do this for individual routes with beforeEnter:

{
    path: '/',
    name: 'home',
    component: Home,
    async beforeEnter(to, from, next) {
      // same axios call & next usage as above example
    }
}

Sign up to request clarification or add additional context in comments.

1 Comment

Did this answer solve your problem? Please checkmark this answer and this will help other people as well. You can do so like this. Or let me know if anything is unclear.

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.