Skip to content
Advertisement

trying to display data but code is not working properly

I am using vue to display data , here is my html

<div v-for="item in secondary">
  <span class="label">
    {{ item.label}}
  </span>
  <span class="value">
    {{ item.value }}
  </span>
</div>

now i have this in computed:

computed : {
  secondary() {
    return this.fetchData;
  } 
}

and in my methods i have this

async fetchData() {
  await this.fetchDetails().then((res) => {
    const sItems = [];
                
    Object.entries(res).forEach(([key, val]) => {
      if (key.startsWith('s'))
        sItems.push({ label: key, value: val });
    });
    return sItems;
  });
},

and now here are some of the things i have issues with, when i loop over the values, my data is not visible, i can see the call to the API which returns me the data

{"secondaryName":"","secondaryInstitution":"","secondaryNumber":"","secondaryNumber":""}

what i am doing wrong here

Advertisement

Answer

Try this :

new Vue({
  el: '#app',
  data: {
    secondary: null
  },
  mounted() {
    this.invokeAPI();
  },
  methods: {
    invokeAPI() {
      // I am assigning the response directly but you can do it by making an API call
      const res = {"secondaryName":"","secondaryInstitution":"","secondaryNumber":"","secondaryNumber":""};

      const sItems = [];

      Object.entries(res).forEach(([key, val]) => {
        if (key.startsWith('s'))
          sItems.push({ label: key, value: val });
      });

      this.secondary = sItems;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(item, index) in secondary" :key="index">
    <span class="label">
      {{ item.label}}
    </span>
    <span class="value">
      {{ item.value }}
    </span>
  </div>
</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement