简体   繁体   English

如何从调用函数之外的axios响应中获取数据

[英]How to get data from axios reponse outside the call function

I'm trying to get a video title from a axios GET to a video API: 我正在尝试将视频标题从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

}

Console log shows the title, but I need to pass this to outside the call function, to have it available in my Vue app. 控制台日志显示了标题,但我需要将此标题传递给call函数之外,以使其在我的Vue应用程序中可用。

I've tried declaring var self=this but it does not seem to have any effect. 我尝试声明var self=this但似乎没有任何效果。 Have I missed something? 我错过了什么吗?

Well, returns nothing because you are not assigning any value to the variable, you will have to assign the response data to a variable when the request fulfill: 好吧,什么也不会返回,因为您没有为变量分配任何值,所以当请求满足时,您将必须将响应数据分配给变量:

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

}

Then, when the promise (the request) is resolved you can access to the variable from the component ( this.title ) 然后,在解决了诺言(请求)后,您可以从组件( this.title )访问变量。

You don't have to use the self switch if you are using arrow syntax. 如果您使用的是箭头语法,则不必使用自我开关。

You're returning title, when assigning the response to this.title , try returning this.title . 您正在返回标题,将响应分配给this.title ,请尝试返回this.title I am making an assumption that latestVideo lives inside a class 我以为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
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM