In my Test.vue
component, I have a method that is imported into my main.js
. I can call its methods like this: this.$refs.test.testMethod()
.
There is another method in Test.vue
called ajaxMethod()
, which is defined as follows:
function ajaxMethod(){
this.$http.post(url).then(function(res){ return "hi from test"})
}
When I make an AJAX call from my main method (in main.js
) like this:
this.$http.post(url).then(function(response){
let a = this.$refs.test.ajaxMethod()
console.log(a) //a is undefined
})"
I attempted to set the value of a variable in Test.vue
and then access it from main.js
like so:
//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'
})"
The expected outcome of the ajaxMethod()
call is 'hi from test' instead of undefined
EDIT
To resolve this issue, I found a workaround using the following code:
a.then(function(val){console.log(val)})
It seems that using the value in a promise
was necessary, but I'm curious if there is a more conventional solution?