Filtering an Array with Computed Properties in Vue

When creating the resources section of my site I wanted to filter the array of resources by the chosen tag. In Vue we can use Computed Properties to filter the array without modifying the original array. The other benefit of using computed peropties is that we can add some animations or transitions when filtering the array.

What is a computed property?

Vue comes packed in with a wondeful templating syntax. The issue is when we have "complex" data we need to represent in the HTML. Sometimes we need to apply a little logic to some templates before rendering them in the DOM. This is where we use computed properties. An simple example would be if we had user's first and last name as seperate properties on an object but wanted a concatenated string rendered in the DOM. The following example is ripped directly from Vue's docs.

computed: {
    fullName: {
      // getter
      get() {
        return this.firstName + ' ' + this.lastName
      },
      // setter
      set(newValue) {
        // Note: we are using destructuring assignment syntax here.
        [this.firstName, this.lastName] = newValue.split(' ')
      }
    }
  }

Filtering an Array with Computed Properties

I'm going to assume your familiar with Filter and Includes for the purposes of this demo.

computed: {
    filterByCat: function () {
      if (
        this.value.drop === 'All'
      ) {
        return this.resources.resources
      } else {
        return this.resources.resources.filter((resource) =>
          resource.tag.includes(this.value.drop)
        )
      }
    },
  }

In this example resources.resources is an array of the resources you will find on my site. Each has an array of tags that we need to check to see if it matches what what the user selected (this.value.drop). I added a simple if/else because I don't use All as a tag so it won't ever match the drop down and I found this to be a simple way to get the array to be unfiltered.
Finally we just need to attach the computed property to the array loop in question.

<Resource
        v-for="resource in filterByCat"
        :key="resource.name"
        :title="resource.name"
        :image="resource.thumbnail"
        :link="resource.link"
        :alt="resource.alt"
        :tag="resource.tag"
        :text="resource.description"
        :data-index="index"
></Resource>