JAVASCRIPT
Efficiently Filter and Sort Lists with Vue 3 Computed Properties
Master how to use Vue 3 computed properties to reactively filter and sort arrays, creating dynamic and responsive lists based on user input or state changes.
<script setup>
import { ref, computed } from 'vue';
const items = ref([
{ id: 1, name: 'Apple', category: 'Fruit', price: 1.20 },
{ id: 2, name: 'Banana', category: 'Fruit', price: 0.75 },
{ id: 3, name: 'Carrot', category: 'Vegetable', price: 0.50 },
{ id: 4, name: 'Broccoli', category: 'Vegetable', price: 1.10 },
{ id: 5, name: 'Orange', category: 'Fruit', price: 1.50 }
]);
const filterText = ref('');
const sortBy = ref('name'); // 'name', 'price'
const sortOrder = ref('asc'); // 'asc', 'desc'
const filteredItems = computed(() => {
const text = filterText.value.toLowerCase();
return items.value.filter(item =>
item.name.toLowerCase().includes(text) ||
item.category.toLowerCase().includes(text)
);
});
const sortedAndFilteredItems = computed(() => {
const itemsToSort = [...filteredItems.value]; // Create a copy to avoid mutating original
return itemsToSort.sort((a, b) => {
let result = 0;
if (sortBy.value === 'name') {
result = a.name.localeCompare(b.name);
} else if (sortBy.value === 'price') {
result = a.price - b.price;
}
return sortOrder.value === 'asc' ? result : -result;
});
});
</script>
<template>
<div>
<input v-model="filterText" placeholder="Filter items by name or category" />
<div>
Sort By:
<select v-model="sortBy">
<option value="name">Name</option>
<option value="price">Price</option>
</select>
<select v-model="sortOrder">
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
</div>
<ul>
<li v-for="item in sortedAndFilteredItems" :key="item.id">
{{ item.name }} ({{ item.category }}) - ${{ item.price.toFixed(2) }}
</li>
<li v-if="sortedAndFilteredItems.length === 0">No items found.</li>
</ul>
</div>
</template>
How it works: This snippet demonstrates how to leverage Vue 3's `computed` properties to create dynamic, derived states for lists. It chains two computed properties: `filteredItems` filters the original array based on `filterText`, and `sortedAndFilteredItems` then sorts the already filtered list based on `sortBy` and `sortOrder`. This approach ensures that the list is reactively updated whenever `filterText`, `sortBy`, or `sortOrder` changes, providing an efficient way to manage complex list manipulations.