How to filter a list with Vue.js?

Sometimes, we want to filter a list with Vue.js.

In this article, we’ll look at how to filter a list with Vue.js.

How to filter a list with Vue.js?

To filter a list with Vue.js, we can use a computed property.

For instance, we write

<template>
  <div id="app">
    <div v-for="item in filteredItems">
      <p>{{ item.name }}</p>
    </div>

    <input type="text" v-model="search" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      search: "",
      items: [
        { name: "for dummies", type: "book" },
        { name: "finding nemo", type: "movie" },
        { name: "leonardo di caprio", type: "actor" },
      ],
    };
  },

  computed: {
    filteredItems() {
      return this.items.filter((item) => {
        return item.type.toLowerCase().includes(this.search.toLowerCase());
      });
    },
  },
};
</script>

to define the search and items reactive properties.

Then we define the filteredItems computed property that returns an array that has the values from items that matches what’s being typed in the input.

This is because we bound the search reactive property to the input value with v-model.

We call toLowerCase on item.type and search to do a case insensitive comparison.

In the template, we render the filteredItems items with v-for.

Conclusion

To filter a list with Vue.js, we can use a computed property.