Sherly Septiani
Sherly Septiani

Reputation: 59

v-for on the same level with v-if affects v-else

If I do this:

<ul>
<li v-for="value in testData">
  <span v-if="Array.isArray(value)" v-for="morevalue in value"> {‌{ morevalue }}</span>
  <span v-else> {‌{ value }} </span>
</li>
</ul>

The span in v-else will also be looped ON THE SECOND V-FOR even though it doesn't have any v-for on it, why?

This is the Vue instance:

new Vue({
    el: '#exercise',
    data: {
        testData: {
        name: 'TESTOBJECT', 
        id: 10,
        data: [1.67, 1.33, 0.98, 2.21]
        }
    }
});

Upvotes: 2

Views: 6606

Answers (2)

Sb. R
Sb. R

Reputation: 31

Can you try something like that:

<div v-if="!!arr?.length">
  <ul>
    <li v-for="value in arr">

      // ...

    </li>
  </ul>
</div>

Upvotes: 1

Gokul Chandrasekaran
Gokul Chandrasekaran

Reputation: 545

v-for has a higher priority than v-if, (ie) v-if will be executed for each loop. If you want to skip execution of the v-for based on the v-if. I would recommend nesting the loop within the condition.

<ul>
<li v-for="value in testData">
  <template v-if="Array.isArray(value)"> 
    <span v-for="morevalue in value"> {‌{ morevalue }} ></span>
  </template>
  <span v-else> {‌{ value }} </span>
</li>
</ul>

Upvotes: 4

Related Questions