Skip to content
Advertisement

Iterating over keys instead of values Vue app

I’m trying to select the values for three keys from my api with axios. Each time I make a request I’m displaying the values four times for each key. I dropped a key from my data models and I re tested. When I did that my request displayed three times instead of four. Meaning I’m iterating over the keys instead of the values.

How Can I change this code to display only the values of each key? I am using nuxt django and axios.

This is the json data axios returns. {"id":1,"balance":10.0,"exposure":7.0,"free_funds":80.0}

How do I just get the values only for each paragraph tag instead of the values for each paragraph tag 4 times?

  <template>
    <div class="container">
      <h2>Current Balance</h2>
      <ul class="trendings">
        <li v-for="result in results" :key="result">
          <p>{{ results.balance }} balance</p>
          <p>{{ results.free_funds }} free_funds</p>
          <p>{{ results.exposure }} exposure</p>
        </li>
      </ul>
    </div>
  </template>


  <script>
  import axios from "axios";
  export default {
    asyncData() {
      return axios.get("http://localhost:8000/api/balance/1").then(res => {
        return { results: res.data };
      });
    }
  };
  </script>

Advertisement

Answer

If the JSON response looks exactly like this:

{"id":1,"balance":10.0,"exposure":7.0,"free_funds":80.0}

Then you don’t even need the v-for because there is only one thing to iterate over.

If you want a v-for, force the data to come back as an array by wrapping it so that it would be this:

[ {"id":1,"balance":10.0,"exposure":7.0,"free_funds":80.0} ]

So:

return { results: [res.data] };
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement