Blog>
Snippets

Combining v-for with Vue's reactive computed properties

Demonstrate how to render a list based on a computed property that reacts to changes in the data.
<template>
  <div>
    <!-- Loop through the computed property 'filteredItems' using v-for -->
    <ul>
      <li v-for="item in filteredItems" :key="item.id">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>
This part contains the Vue template with an unordered list (ul). The v-for directive is used to loop over the items of the 'filteredItems' computed property, rendering each 'item' as a list element (li).
<script>
import { defineComponent, ref, computed } from 'vue';

export default defineComponent({
  name: 'ItemList',
  setup() {
    // Reactive data property
    const items = ref([
      { id: 1, name: 'Item 1', category: 'A' },
      { id: 2, name: 'Item 2', category: 'B' },
      { id: 3, name: 'Item 3', category: 'A' }
    ]);

    // Reactive computed property that filters the items by a certain category
    const filteredItems = computed(() => {
      return items.value.filter(item => item.category === 'A');
    });

    // Expose to the template
    return {
      filteredItems
    };
  }
});
</script>
This script section of the Vue component defines the reactive data properties and computed properties. In the setup function, 'items' is a reactive array of objects. 'filteredItems' is a computed property based on 'items', which automatically updates when 'items' changes. It filters for items with category 'A' and is made available to the template for rendering.