[英]ajax call inside another ajax call returns undefined
我在Test.vue
組件中有一個方法。 我將其導入到main.js
,可以調用其方法: this.$refs.test.testMethod()
。
我在Test.vue
有一個方法ajaxMethod()
看起來像這樣:
function ajaxMethod(){
this.$http.post(url).then(function(res){ return "hi from test"})
}
現在,我像這樣從我的main方法(在main.js
)進行ajax調用:
this.$http.post(url).then(function(response){
let a = this.$refs.test.ajaxMethod()
console.log(a) //a is undefined
})"
我試圖在Test.vue中設置變量的值,然后像這樣從main.js中讀取它:
//in Test.vue
data:{
variable:""
}
methods:{
function ajaxMethod(){
this.$http.post(url).then(function(res){
this.variable="hi from test"
})
}
}
//in main.js
this.$http.post(url).then(function(response){
this.$refs.test.ajaxMethod()
console.log(this.$refs.test.variable) //when i call that function first time result is empty string and when i call it second time result is 'hi from test'
})"
我希望ajaxMethod()
返回'hi from test'不是undefined
編輯
我可以使用以下解決方法解決此問題:
a.then(function(val){console.log(val)})
據我了解,我在promise
使用了價值,那還好嗎,或者還有另一個“適當”的解決方案?
您沒有從ajaxMethod返回任何東西。 而且,您不應該這樣耦合您的組件。 注意同步和異步代碼塊。 post方法返回一個promise,而不是值。 您可以在回調函數中獲取該值。
function ajaxMethod(){
return this.$http.post(url);
}
你需要兌現承諾
this.$refs.test.ajaxMethod().then(function(res){
console.log(res)
})
然后獲得價值。 我不知道確切的情況,但我認為您應該使用事件將數據從子級發送到父級,而不是這種方式。
編輯進行編輯:正如我所說,您應該使用事件而不是這種方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.