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.
2 Answers
Reset to default 3It'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.