簡體   English   中英

如何在 Vue-router 中使用 $router.push?

[英]How to use $router.push in Vue-router?

我需要在 Vue-router 中使用$router.push 檢查我的代碼:

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

我的問題是如何在這個文件中使用$router.push 檢查我的路由器:

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

您可以使用路線導航守衛來做到這一點。

這是一個使用beforeEach的人為示例(在每條路線之前運行):

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

這將在導航到每個路由之前運行一個異步調用,然后檢查響應數據。 如果一切正常,導航將繼續。 否則,用戶將被重定向回主路由。

您可以使用beforeEnter對單個路由執行此操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM