【问题标题】:axios call from index.js vue - this is undefined来自 index.js vue 的 axios 调用 - 这是未定义的
【发布时间】:2021-10-22 12:41:17
【问题描述】:

在我的 vue 项目中,我需要检查每条路线的 jwt 令牌,因此在 beforeEach 方法中,如果 jwt 令牌未保存在 localStorage 中,我将向后端发送请求。这是我来自src/router/index.js的代码:

router.beforeEach((to, from, next) => {

  if (to.meta.authRequired) {

    const jwt = localStorage.getItem('jwt');

    if (!jwt) {
       this.$axios.get(`/api/users/jwtWithoutLogin`,{
        }).then((response) => {
            localStorage.setItem('jwt', response.data.jwt)
          });   
            
    }

    const payload = JSON.parse(atob(jwt.split('.')[1]));
    const username = payload.username
    console.log(username)
    localStorage.setItem("username", username)
  }

  next();
});

但是在浏览器的控制台中我总是出错:

TypeError: _this is undefined

我尝试使用选项self 而不是this,我尝试不使用this,但它不起作用。我也在考虑在 beforeEach 方法中删除这个 axios 调用,但我不知道每次页面加载时我还能把它放在哪里调用?

【问题讨论】:

    标签: vue.js axios this vue-router


    【解决方案1】:

    你可以尝试在router中导入axios:

    import axios from 'axios'
    

    然后使用它:

    axios.get(`/api/users/jwtWithoutLogin`,{
      ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-01
      • 2020-05-06
      • 2019-01-05
      • 1970-01-01
      • 2023-03-26
      • 2021-11-04
      • 2023-03-03
      • 2019-02-06
      相关资源
      最近更新 更多