vue filter()
<template>
<div>
<ul>
<li v-for="item in filteredItems" :key="item.id">
{{ item.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Apple', category: 'fruit' },
{ id: 2, name: 'Carrot', category: 'vegetable' },
{ id: 3, name: 'Orange', category: 'fruit' },
{ id: 4, name: 'Broccoli', category: 'vegetable' },
],
filterCategory: 'fruit',
};
},
computed: {
filteredItems() {
return this.items.filter(item => item.category === this.filterCategory);
},
},
};
</script>
This example demonstrates the use of a Vue filter to display a list of items based on a selected category. The component has a data property named items
, an array of objects representing items with their respective id
, name
, and category
. It also has a filterCategory
property initialized with the value 'fruit'
.
In the template, a list (<ul>
) is rendered using v-for
to iterate over the computed property filteredItems
. Each item's name is displayed within a list item (<li>
).
The filteredItems
computed property filters the items
based on the filterCategory
. It uses the Array.filter()
method to create a new array containing only the items whose category
matches the filterCategory
. The filtered array is then rendered in the template.