Sometimes, we want to render a filtered list of array elements in our Vue component.
In this article, we’ll look at how to render a filtered list of array elements in our Vue component.
Filtering Lists in Vue Components
The proper way to filter lists is to use a computed property.
This is because computed properties return a value before v-for
is run.
For instance, we can write:
computed: {
filteredItems() {
return this.items.filter(item => item.type.toLowerCase().includes(this.search.toLowerCase()))
}
}
We put our filtering logic in the filterItems
computed properties.
Then we can loop through the computed properties by writing:
<div v-for="item of filteredItems" >
<p>{{item.name}}</p>
</div>
We just pass in the filteredItems
computed property as a variable into our template.
Conclusion
The proper way to filter lists is to use a computed property.