【问题标题】:Accessing variable from outsite of axios post从 axios post 外部访问变量
【发布时间】:2020-06-05 18:07:36
【问题描述】:

我正在尝试访问 axios 调用中的变量,但它返回 undefined 错误。请在下面查看我的代码。

new Vue({
   el: '#app',
   data(){
     return {
       roles: [{ display: 'disp' }]
     }
   },
   methods: {
      axios.post('{{ route('role.add') }}', {

      })
      .then((response, roles) => {
            console.log(this.roles);

      })
       .catch(function(err){
          console.log(err);
       });
   }

})

错误

未定义

解决方案 [已解决]

  • 在 Vue 上方添加了全局变量。

【问题讨论】:

  • 为什么要this.,如果您尝试访问看似简单的局部变量?
  • 或者你是想访问匿名回调函数声明中指定的参数roles?那么this. 仍然是错误的。而且我很怀疑是否有任何这样的第二个参数会被传递给回调,我看不出这里应该首先触发什么。
  • @CBroe 请查看我的更新。
  • 你想要什么在你的控制台

标签: javascript vue.js axios


【解决方案1】:

尝试在没有this 的情况下访问。我认为使用 this 没有任何目的。

const axios = require("axios");
var a = "some value";

axios.get('http://www.google.com').then(function () {

    console.log(a);
}).catch(e => {
    console.log(e, "ERROR");
})

【讨论】:

  • 尝试访问roles 而不是this.roles
  • 我尝试使用roles,但仍然遇到同样的错误。
  • promise 无法同时解析这两个值,请根据分辨率添加 [response, roles]response。也许只有response
  • 您可以使用response.data.roles 访问。但我不确定您的路线发送的响应结构
【解决方案2】:

只需删除此关键字,它就会起作用:

var roles = [{ display: 'disp' }];

axios.post('{{ route('role.add') }}', {

})
.then(function(response){
     console.log(roles);
})
.catch(function(err){
     console.log(err);
});

或者使用不喜欢的箭头功能:

var roles = [{ display: 'disp' }];

axios.post('{{ route('role.add') }}', {

})
.then((response, roles) => {
     console.log(this.roles);
})
.catch(function(err){
     console.log(err);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2015-03-05
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2011-04-15
    相关资源
    最近更新 更多