0 day streak
javascript / beginner
Snippet

Reactive List Filtering with Computed Properties

Using JavaScript's built-in array methods like filter inside a computed property allows you to create reactive, derived lists that update automatically when either search inputs or data change.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { ref, computed } from 'vue';
const searchQuery = ref('');
const items = ref([
{ id: 1, name: 'Apple', inStock: true },
{ id: 2, name: 'Banana', inStock: false },
{ id: 3, name: 'Avocado', inStock: true }
]);
const filteredInStockItems = computed(() => {
return items.value
.filter(item => item.inStock)
.filter(item => item.name.toLowerCase().includes(searchQuery.value.toLowerCase()));
});
vue
Breakdown
1
const searchQuery = ref('');
Creates a reactive string reference to store the user search query.
2
const items = ref([ ... ]);
Initializes a reactive array of objects containing product data.
3
const filteredInStockItems = computed(() => {
Defines a memoized computed property that tracks dependencies and recalculates only when necessary.
4
return items.value.filter(item => item.inStock)
Applies the native array filter method to retain only in-stock items.
5
.filter(item => item.name.toLowerCase().includes(searchQuery.value.toLowerCase()));
Chains a second filter to match item names against the query in a case-insensitive manner.