🎓 A1Learner
🔍
0 of 50 lessons completed

Filtering Lists in Vue

Filtering a list shows only the items that match a rule. A computed value builds the shorter list from the full list.

The filtered list

shown keeps only the fruits that match the search.

const shown = computed(() =>
  fruits.value.filter((fruit) => fruit.includes(query.value))
)

Render the short list

v-for renders the filtered list.

<li v-for="fruit in shown" :key="fruit">{{ fruit }}</li>

The search box

The box links to the search word.

<input v-model="query">

Example

<script setup>
import { ref, computed } from 'vue'
const query = ref('')
const fruits = ref(['Apple', 'Banana', 'Cherry'])
const shown = computed(() => fruits.value.filter((fruit) => fruit.includes(query.value)))
</script>
<template>
  <div>
    <label>Search <input v-model="query"></label>
    <ul>
      <li v-for="fruit in shown" :key="fruit">{{ fruit }}</li>
    </ul>
  </div>
</template>

Key points

  • A computed value is a value that Vue works out from other values, and it updates when they change.
  • Array.filter is a method that keeps the matching items only.
  • The test is a small function. It returns true for items to keep.
  • filter builds a new array, so the first list stays whole.
  • The page renders the filtered list with v-for, like any other list.

In this example, query is a ref that starts as an empty string. fruits is a ref that holds three words. shown is a computed value that keeps only the fruits that hold the search word. The search box links to query, and the list renders shown. The page starts with all three fruits. Searching for a leaves only Banana, because only Banana holds the small letter a.

Note

An empty search shows every item.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does the page show only the matching fruits?