Background
In vue, we use the v-for
directive to loop through an array and display the items in the browser.
Here is an example. We loop through the items
array and display the item name in a list.
<ul>
<li v-for="item in items" :key="item.name">
{{ item.name }}
</li>
</ul>
In Practice
In practice, the items
array could come from the api (our backend). It could contain any number of items that we eventually display in the browser. It could contain 10, 5 or zero items in which case we display nothing.
However, what if we want to display a minimum number of items regardless of how many items are in the array.
In our UI, we want to avoid situations when nothing is rendered or too few items are rendered.
Placeholders
In these situations, we can use placeholders. They could be dummy items or empty div
s. They might be used to fill the empty space or if the design requires there to be a minimum number of items displayed. They could also indicate to users that there could be more items or they (users) can add more.
If the items array is empty, then we display five placeholders, and if it contains three items, we display two placeholders and so on.
How the code looks like
Now, let's see how we can go about implementing it in the frontend.
First, I will have the same loop in the top to loop through the items. Then I will have a separate loop to display placeholders if needed.
As for the placeholders, I will use empty li
s with some styling.
<ul>
<li v-for="item in items" :key="item.name">
{{ item.name }}
</li>
</ul>
<ul v-if="placeholder">
<li v-for="(n, i) in placeholder" :key="i" class="block">
</li>
</ul>
Here are the styles for block
.block {
background: grey;
height: 15px;
width: 50px;
}
placeholder
would be a computed property. Whereas, items
could either be a local data or coming form store if using a global state like Vuex.
placeholder() {
// a max of 5 slots when no items at all!
if (this.items && this.items.length < 5) {
return 5 - this.items.length;
} else {
return 0;
}
},
this.items
refers to the items array.
Now, placeholders will show if we have five items or less.
Thanks for reading
Top comments (0)