【问题标题】:How to get data from axios reponse outside the call function如何从调用函数之外的axios响应中获取数据
【发布时间】:2018-11-14 21:40:39
【问题描述】:

我正在尝试将视频标题从 axios GET 获取到视频 API:

// METHOD GETTING A VIDEO ID:

latestVideo(videoID) {

  var self = this;
  var title;

  axios.get('http://video-api.dev/'+videoID)
  .then(response => {
    this.title = response.data.title
    console.log(response.data.title) //returns the correct title
  })
  return title // returns nothing

}

控制台日志显示标题,但我需要将其传递到调用函数之外,以便在我的 Vue 应用程序中使用它。

我尝试过声明var self=this,但它似乎没有任何效果。我错过了什么吗?

【问题讨论】:

标签: javascript vue.js axios


【解决方案1】:

好吧,因为您没有为变量分配任何值,所以什么也不返回,您必须在请求完成时将响应数据分配给变量:

latestVideo(videoID) {

  // var self = this;
  // var title;

  axios.get('http://video-api.dev/'+videoID)
  .then(response => {
    this.title = response.data.title
    console.log(response.data.title) //returns the correct title
  })
  // return title // not needed

}

然后,当 promise(请求)被解决后,您可以从组件中访问变量 (this.title)

如果您使用箭头语法,则不必使用 self 开关。

【讨论】:

  • response在声明变量时没有定义
  • @FilipBlaauw 在这种情况下,title 将始终未定义,因为您正在处理异步数据。您应该在 then 的回调中返回 title
  • 没错,我会改变答案
【解决方案2】:

您正在返回标题,在将响应分配给 this.title 时,请尝试返回 this.title。 我假设latestVideo 生活在一个类中

class x {

latestVideo(videoID) {
    axios.get('http://video-api.dev/'+videoID)
    .then(response => {
        this.title = response.data.title
        console.log(response.data.title) //returns the correct title
    });

    return this.title
}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2020-03-22
    • 2019-11-26
    • 1970-01-01
    • 2023-03-25
    • 2019-12-02
    • 2020-09-01
    相关资源
    最近更新 更多