简体   繁体   中英

How to use $router.push in Vue-router?

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
}]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM