admin管理员组

文章数量:1327476

I faced a really silly problem today and just sharing it here:

v-for and v-if doesn't work together when its data value is []. For eg:

ts: []

<div v-for="t in ts" :key="t" v-if="ts.length">
  Yes
</div>
<div v-else>
  No
</div>

See it in action here in codesandbox.

We can see nothing is rendered and even no error is thrown. I also tried with v-if="ts.length > 0" but it still renders nothing.

I faced a really silly problem today and just sharing it here:

v-for and v-if doesn't work together when its data value is []. For eg:

ts: []

<div v-for="t in ts" :key="t" v-if="ts.length">
  Yes
</div>
<div v-else>
  No
</div>

See it in action here in codesandbox.

We can see nothing is rendered and even no error is thrown. I also tried with v-if="ts.length > 0" but it still renders nothing.

Share Improve this question asked Nov 11, 2018 at 16:28 Bhojendra RauniyarBhojendra Rauniyar 85.7k36 gold badges177 silver badges239 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

It's not remended to use v-for with v-if . see official docs: https://v2.vuejs/v2/guide/conditional.html#v-if-with-v-for

One possible solution is to separate v-if from v-for like this:

<div v-if="ts.length">
  <div v-for="t in ts" :key="t">
    Yes
  </div>
</div>
<div v-else>
  No
</div>

But this seems to be bad solution for me while others can use it as a good solution. Because I was needed to use v-for and v-if together. Its because I don't like to separate pieces from file and just need to use inside table's tr ponent.

Though, we agree from the documentation states: Never use v-if on the same element as v-for.

本文标签: javascriptvfor and vif not working together when data gets empty arrayStack Overflow