У меня есть метод в Test.vue
компоненте.Я импортировал его в свой main.js
и могу вызывать его методы следующим образом: this.$refs.test.testMethod()
.
У меня есть метод ajaxMethod()
в Test.vue
, который выглядит следующим образом:
function ajaxMethod(){
this.$http.post(url).then(function(res){ return "hi from test"})
}
Теперь я делаю ajax-вызов из моего основного метода (который находится в main.js
) следующим образом:
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()
вернет 'привет из теста', а не undefined
РЕДАКТИРОВАТЬ
Я могу решитьэто с помощью этого обходного пути:
a.then(function(val){console.log(val)})
как я понимаю, я использовал значение в promise
, это нормально или есть другое "правильное" решение?