2

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]
        }
    }
});

2 Answers2

4

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>
  • However, your code is right, the justification is wrong. The v-if is the one with higher priority, this means will run first that the v-for. Source: https://vuejs.org/guide/essentials/list.html#v-for-with-v-if – XAronX Nov 28 '22 at 10:45
1

Can you try something like that:

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

      // ...

    </li>
  </ul>
</div>
S. zbr
  • 31
  • 2