javascript / beginner
Snippet
Filtering List Items with Array Filter in Computed Properties
The computed() function tracks reactive dependencies and automatically re-evaluates when they change. Using JavaScript's built-in Array.prototype.filter() method inside a computed property allows you to create a derived list of pending tasks without mutating the original reactive array.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { ref, computed } from 'vue';const tasks = ref([{ id: 1, title: 'Write tests', isDone: true },{ id: 2, title: 'Review pull request', isDone: false }]);const pendingTasks = computed(() => {return tasks.value.filter(task => !task.isDone);});
vue
Breakdown
1
const tasks = ref([
Declares a reactive array containing task objects.
2
const pendingTasks = computed(() => {
Creates a cached computed property that recalculates whenever tasks changes.
3
return tasks.value.filter(task => !task.isDone);
Uses the native array filter method to return only tasks where isDone is false.