With the v-for directive, you can easily render all the items of an array in Vue.js. But what if you don’t want to show the complete list but only the first n items?
There could be a situation, for instance, where you have a huge list of items but you only want to show the first n items of it.
Let’s say you have a list of the top 10 fastest cars in the world. Now you want to show only the top 5 for some reason. You can of course take a local state or a temporary variable where you can get the first 5 items and then show them on the list. But, that comes with the expense of one extra variable, plus the rendering time. Another possibility would be to truncate the original variable containing the list and have it rendered directly. But that comes with the cost of data loss. Here I’m showing a way to display only the number of items you want to be displayed without having to deal with any of the said solutions:
<template>
<div>
<ul>
<li v-for="(item, index) in getShortList(5)" :key="index">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
name: "ShortenedList",
data() {
return {
myList: [
"Koenigsegg Jesko Absolut",
"Bugatti Chiron Super Sport",
"SSC Tuatara",
"Hennessey Venom F5",
"Aston Martin Valkyrie",
"McLaren Speedtail",
"Koenigsegg Gemera",
"Pagani Huayra BC Roadster",
"Rimac Concept_One",
"Lamborghini Sian Roadster",
],
};
},
methods: {
getShortList(shortListSize) {
return this.myList.slice(0, shortListSize);
},
},
};
</script>
Code language: HTML, XML (xml)
In the above code, I have a list of 10 fastest cars in the world, but I’m only rendering the first 5. I’ve used a method named getShortList() on line 4. Inside the method definition, I’ve sliced the list array and returned it directly to the rendering list, without storing it anywhere else. The scope of the passed variable remains within the scope of this mounted component only.
You can find the working code from the following links: