As stated in #677 currently you have to wrap a v-for with an if to catch if an array is empty. I'd love a tag like v-empty to do that. It would work like v-else and you put it right after a v-for (maybe also v-else could also be reused for that?).
The v-empty block triggeres if the v-for list is empty. Just like the equivalent django template tag: https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#for-empty
Example:
<div v-for="(index, item) in items">
{{ index }} {{ item.message }}
</div>
<div v-empty>
<p>Sorry, no elements yet.</p>
</div>
While I'm a fan of little utilities like this, a client-side JavaScipt library shouldn't cover them due to size and performance issues. Server-side frameworks like Laravel and Django, on the other hand, have all my support.
@asmaps You could also simply use v-if or v-show.
<div v-for="(index, item) in items">
{{ index }} {{ item.message }}
</div>
<div v-if="items.length == 0">
<p>Sorry, no elements yet.</p>
</div>
If you needed to handle both Arrays and Objects, a basic method implementation could be:
{
isEmpty (value) {
if (!!value && value instanceof Array) {
return value.length < 1
}
if (!!value && typeof value === 'object') {
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false
}
}
}
return !value // Fallback for strings, etc.
}
}
@taylorzane sure I can use v-if. For v-else it's the same, I could also use v-if="!ifCondition" instead of v-else, but it's a convenience feature and prevents code duplication.
With @phanan s reason you could also argue against v-else. But yes, somewhere a line has to be drawn. If it's here that's okay for me, just wanted to ask because I'm used to it from django and find it very useful.
With @phanan s reason you could also argue against
v-else.
Exactly. And that's why we had internal discussions about v-else as well ;)
performance issues
@phanan - do you mean the overall size of the library or do you mean rendering performance? This doesn't seem like it would be any more intensive than a v-if/v-else or v-if/v-for.
Also, maybe this could be implemented as a plugin?
do you mean the overall size of the library or do you mean rendering performance?
I meant both, regarding those small utilities.
Most helpful comment
Exactly. And that's why we had internal discussions about
v-elseas well ;)