vue监听接口状态

  data () {
    return {
      time: false // 判断
    }
  },
methods: {
    dinshi () {
      if (this.time === true) {//判断是否超时
        console.log('超时')
        this.$router.push({//跳转页面
          path: `/error`
        })
      } else {
        console.log('没超')
      }
    }
  },
created () {
    axios.interceptors.request.use(config => { // 请求拦截
      // console.log('请求拦截器:')
      this.time = true
      sessionStorage.setItem('error', JSON.stringify(this.$route.path))//储存当前页面链接
      setTimeout(this.dinshi, 10000)//调用判断时间
      return config
    })
    axios.interceptors.response.use( // 响应拦截
      response => {
        // console.log(response)
        // console.log('响应拦截器:')
        if (response.status === 200) {//正常
          this.time = false
          return Promise.resolve(response)
        } else {
          return Promise.reject(response)
        }
      },
      error => { //异常
        if (error.response.status) {
          this.$router.push({//跳转404
            path: `/error`
          })
          switch (error.response.status) {
            case 404:
              console.log('404')
              break
            // 其他错误,直接抛出
            default:
          }
          return Promise.reject(error.response)
        }
      }
    )
  }
发布了31 篇原创文章 · 获赞 32 · 访问量 1173

猜你喜欢

转载自blog.csdn.net/weixin_45936690/article/details/104702017
今日推荐