Computed properties are part of Vue.js’s core functionality, but much of what they do can be done with a normal method, so how do you know when to use one over the other?

Computed Properties vs Methods

A computed property is cached based on it’s dependencies, that means that it doesn’t re-run the computed until one of it’s dependencies is updated, which makes computed properties more efficient. As a basic example, let’s write a computed that takes a blog title and returns a slug:

computed: {
  slug() {
    let slug = this.title.replace(/[^a-z0-9\s]/ig,"");
    return slug.toLowerCase().replace(/\s/g, "-");
  }
},
data: {
  title: "Understanding Computed Properties"
}

With this code the computed is run once and then simply returns the same value each subsequent time it’s called, it doesn’t run that code again until the value of “title” changes. If we were to write a method, the code would run each time we ask for the slug. Take a look at this JSFiddle, which prints the slug on the page twice for both a computed property and a method and counts how many calls were made for each: https://jsfiddle.net/vuetiful/6khxa070/

As you can see the method runs twice as many times of the computed, if you are performing expensive tasks then retrieving the cached value is vastly preferable.

One thing to watch out for is that computed properties are updated based on reactive dependencies, which means that if you are doing something that does not rely on a reactive dependency you need to use a method instead.

The following JSFiddle illustrates this with a simple timer: https://jsfiddle.net/vuetiful/xfxzx3tg/

In this example, only the methods timer is updated on the page when the vue instance is re-rendered, the computed timer remains at 0 because the value has been cached and timer is a global non-reactive variable.

Computed Setters

A computed is generally used to arbitrarily manipulate data, which means you usually don’t need a setter, however a computed does allow you to set values. The basic idea is that when you try to manually set the value of the computed, the setter is invoked allowing you to perform update logic.

Let’s take our slug example, using a computed setter we can create a two way binding that both updates the slug when the title changes and updates the title when the slug changes:

 computed: {
    slug: {
      get() {
          let slug = this.title.replace(/[^a-z0-9\s]/ig, "");
          return slug.toLowerCase().replace(/\s/g, "-");
        },
        set(value) {
          // This fires when we try to update slug
          let title = [];
          // Make the first letter of each word upper case
          value.split('-').forEach((item, key) => {
            title[key] = item.charAt(0).toUpperCase() + item.slice(1, item.length);
          });

          this.title = title.join(" ");
        }
    }
  },
  data: {
    title: "Understanding Computed Properties"
  }

Here’s the JSFiddle: https://jsfiddle.net/vuetiful/0dzon3da/

That may not be hugely practical but it illustrates the point. Computed properties generally don’t need a setter, but they are particularly useful in vuex when you want to commit a mutation to your store.

One final note, if you’re still struggling to figure out if you need a method or computed then remember this; if your function is not returning anything or it calculates it’s return value based on a parameter your are passing in, then you need a method. If you are simply performing some manipulation to reactive data to be returned to your view then use a computed.

Advertisements