简体   繁体   中英

Why won't the data from my api render in my Vue template?

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?

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;
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM