sabu monkey
sabu monkey

Reputation: 43

Run a function inside two v-for loop in vue js

I have two v-for loops like so:

<div v-for="id in ids">
        <div v-for="data in getData(id)">
              <p>{{data.name}}</p>
        </div>
</div>

The first v-for iterates through an array of ids stored inside data(). On the second v-for it iterates through the result returned by the function getData().

The axios call does return an array of result including the name per ids, however the <p> tag doesnt display the names.

<script>
    data(){
       id: ['1', '2', '3']
    },
    methods:{
       getData(id){
          //axios call
          return response.data;
       }
    }
</script>

Upvotes: 3

Views: 1358

Answers (1)

hamid niakan
hamid niakan

Reputation: 2851

I think this is the problem:

when v-for calls your method it doesn't wait for axios call to resolve and since there is no array immediately available for it to iterate on, it can't show anything (there isn't anything to show), on the other hand when axios call does resolve there is no way for v-for to get notified and therefore update the template. so situation is something like this:

  1. v-for runs your method
  2. method doesn't return an array immediately and v-for can't wait
  3. there is nothing to show here and it moves on

so here is what you can do:

  1. bind the v-for to an array in data object
  2. use axios result to update the said array

and it should work fine, your code might be like this for example:

// template
<div v-for="data in axiosResult">
   <p>{{data.name}}</p>
</div>

//script
<script>
data(){
   id: ['1', '2', '3'],
   axiosResult: [],
},
methods:{
   getData(){
      //axios call
      this.id.forEach((id) => {
         //axios function for each id
         axiosCall(id).then((result) => {
          this.axiosResult.push(result);
         });
      });
   }
}
</script>

Upvotes: 2

Related Questions