【问题标题】:how to call function inside axios?如何在axios中调用函数?
【发布时间】:2021-02-21 03:22:55
【问题描述】:

我试图在 Axios 中调用一个函数,但它显示未定义。下面是我的简单代码。我正在使用 vuejs。

methods:{
    sett( ){
        console.log("result" )
    },

    List() {
        var self = this;
        axios.get("http://localhost:8080/api/v1/pas/device")
            .then(function(res) {
                self.sett( )
            }
        }
    },
    created: {
        this.List();
    }

【问题讨论】:

  • 请添加更多代码以便理解
  • 尝试使用 await const list = await axios.get("localhost:8080/api/v1/pas/device"); this.sett()
  • 我的答案是第一个正确的,请检查每个答案的时间
  • 你应该接受第一个正确答案并投票赞成

标签: javascript vue.js axios


【解决方案1】:

在axios中使用箭头函数,并以常规方式调用其他函数:

methods:{
  sett( ){
    console.log("result" )
  },
  List() {
    axios.get("http://localhost:8080/api/v1/pas/device")
        .then((res) => {
            this.sett();  // do with res what you want
        });
  }
},
created() {
    this.List();
}

【讨论】:

    【解决方案2】:

    创建的是一个函数

    methods:{
       sett(response){
           console.log(response)
           console.log("result" )
       },
    },
    created() {
       axios.get("http://localhost:8080/api/v1/pas/device").then(this.sett)
    }
    

    【讨论】:

      【解决方案3】:

      created钩子是一个函数而不是一个对象:

      ....
      created:function(){
        this.List()
      } 
      

      或 ES6 简写语法:

      ....
      created(){
        this.List()
      }  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-30
        • 2019-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-31
        • 1970-01-01
        • 2020-03-26
        相关资源
        最近更新 更多