[英]How to get data from axios reponse outside the call function
我正在嘗試將視頻標題從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
}
控制台日志顯示了標題,但我需要將此標題傳遞給call函數之外,以使其在我的Vue應用程序中可用。
我嘗試聲明var self=this
但似乎沒有任何效果。 我錯過了什么嗎?
好吧,什么也不會返回,因為您沒有為變量分配任何值,所以當請求滿足時,您將必須將響應數據分配給變量:
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
}
然后,在解決了諾言(請求)后,您可以從組件( this.title
)訪問變量。
如果您使用的是箭頭語法,則不必使用自我開關。
您正在返回標題,將響應分配給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
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.