VUE中的路由器未定义

时间:2020-02-11 03:57:40

标签: javascript vue.js axios vue-router

我在App.vue中添加了axios拦截器以捕获所有状态401,因此我可以注销用户。我正在尝试重定向到登录页面。我不断收到“无法读取未定义的属性'$ router'”,不确定是什么问题。有什么帮助吗?还有一种更好的方法可以全局处理axios http状态错误。而不是检查发出http请求的每个组件上的状态是否为400401等。

created: function () {
  axios.interceptors.response.use(undefined, function (err) {
    return new Promise(function (resolve, reject) {

      if (err.response.status=== 401 ) {

        this.$router.push({ name: 'loginview' })

    }
      throw err;
   });
  });
}

2 个答案:

答案 0 :(得分:2)

主要问题是this不会引用内部函数中的组件实例。有多种解决方法,例如改为使用箭头功能。

在下面的示例中,我也删除了new Promise,因为这似乎不是必需的。

created: function () {
  // Using an arrow function preserves the 'this' value
  axios.interceptors.response.use(undefined, err => {
    if (err.response.status === 401 ) {
      this.$router.push({ name: 'loginview' })
    }

    // You may not want to return this in the 401 case
    return Promise.reject(err)
  });
}

答案 1 :(得分:0)

您可以执行以下操作:

print(df)
         date  p         p1                       p2
0  2019-12-22  1 2019-12-22  2019-11-24 : 2019-12-22
1  2019-12-15  1 2019-12-22  2019-11-24 : 2019-12-22
2  2019-12-08  1 2019-12-22  2019-11-24 : 2019-12-22
3  2019-12-01  1 2019-12-22  2019-11-24 : 2019-12-22
4  2019-11-24  2 2019-11-24  2019-10-27 : 2019-11-24
5  2019-11-17  2 2019-11-24  2019-10-27 : 2019-11-24
6  2019-11-10  2 2019-11-24  2019-10-27 : 2019-11-24
7  2019-11-03  2 2019-11-24  2019-10-27 : 2019-11-24
8  2019-10-27  3 2019-10-27  2019-10-13 : 2019-10-27
9  2019-10-20  3 2019-10-27  2019-10-13 : 2019-10-27
10 2019-10-13  3 2019-10-27  2019-10-13 : 2019-10-27