Reputation: 62
I've been scratching my head about this for a while. I'm new to Vue and can't seem to understand why this isn't working.
My template...
<template>
<div>
<div v-if="loading" class="loading">Loading...</div>
<div v-if="dbhs">
<h1>adfoij</h1>
<p class="mb-0" v-if="dbhs.length === 0">
You have not any DBHs.
</p>
<div v-else>
<div v-for="dbh in dbhs">{{dbh.dbh}} - {{dbh.count}}</div>
</div>
</div>
</div>
</template>
My script...
<script>
export default {
data() {
return {
loading: true,
dbhs: null
};
},
created() {
this.getDbhs();
},
methods: {
ajaxAxiosGetFunc: async function (url) {
var output = '';
await axios({
method: 'post',
url: url,
data: {},
responseType: 'json',
})
.then(function (response) {
//output = JSON.parse(response.data);
output = response.data;
}.bind(this))
.catch(function (error) {
console.log('ajax error');
});
return output
},
getDbhs: async function(){
var estimate_id = document.getElementById('estimate_id').value
var output = await this.ajaxAxiosGetFunc('/estimate/'+estimate_id+'/getTreesSummary/dbh'); // called asynchronously to wait till we get response back
this.dbhs = output;
console.log(output);
this.loading = false;
},
}
}
</script>
I'm getting data back from the API
... it prints out in the console fine but the length of dbhs
is always 0
.
Anyone have any ideas?
Upvotes: 0
Views: 51
Reputation: 214957
It's because your method uses function
keyword which overrides this
that refers to the vue instance, change your anonymous function to an arrow function should work:
getDbhs: async () => {
var estimate_id = document.getElementById('estimate_id').value
var output = await this.ajaxAxiosGetFunc('/estimate/'+estimate_id+'/getTreesSummary/dbh'); // called asynchronously to wait till we get response back
this.dbhs = output;
console.log(output);
this.loading = false;
},
Upvotes: 1