fbpx

Mastering VueJS Computed Properties

VueJS computed properties can be a lifesaver. There are few things more frustrating to a programmer than staring at a block of code and taking years to decipher what’s going on. When working in VueJS, one of the most common ways to clutter code is to add very long expressions to your template. For example, say we want want to render a reversed string, without spaces, and in all caps. If we were to do this using an in-template expression, it would look like this.

<span>
   {{ text.replace(/ /g, ‘’).split().reverse().join().toUpperCase() }}
</span>

Now you may be more of a CS pro than me, but this is way too cluttered for me to look at a glance and know immediately what it’s trying to do. Now imagine having to use this value in multiple places in a template and having this long expression all over your code. This is when it’s a lifesaver to use VueJS’ computed properties.

Ok, but how do computed properties work?

Now that we know why VueJS computed properties are useful, let’s go over how to use them. In most basic terms, we just add a field to our Javascript exports and define our computed properties there. For the example above, it would look like this.

export default {
   data () {
      text: ‘hello world’
   },
   computed {
      formattedText: function () {
         return this.text.replace(‘ ‘, ‘’).reverse().toUpperCase()
      }
   }
}

Now that we’ve defined our computed property, it becomes super easy to render it in our template. This is all we have to do.

<span>
   {{ formattedText }}
</span>

That’s it. Now, on our webpage, we should render DLROWOLLEH in a much cleaner and readable way. Using computed properties always makes your project more scalable because if we want to change the value rendered, we would only have to change the computed property instead of going through and changing every expression throughout the template.

So, when exactly does the computed property change?

Since a computed property is like a more detailed Vue watcher, it will observe a piece of reactive data and update when that reactive data changes.

For our example, formattedText will always be dependent on the value of text. So if we were to change text to ‘ABCDEF’, then formattedText will return ‘FEDCBA’. However, in order to run more efficiently, VueJS caches computed property values. VueJS will only recalculate the property when a dependency is changed. In our case, it will only recalculate when text changes. Otherwise, it will return the cached value from the last change.

To fully understand when computed properties will change, we have to understand the idea of their dependencies. Simply put, a computed property’s dependencies are the values that help the property that determine the value that is returned. If none of these change, then, again, the cached value will be returned.

If no dependency is changed, a computed property is not recalculated.

The following example from in the VueJS docs shows a computed property that will never recalculate.

computed: {
   now: function () {
      return new Date()
   }
}

Although the computed property now returns a value that changes all the time, there are no dependencies that VueJS watches for. Therefore, it is never recomputed.

If you don’t like this, you can always use a regular VueJS method, which by default is recalculated on every render.

You can also define a setter for a computed property

By default, computed properties are read only and cannot be set. However, if you want to add a hook for a computed property that allows its dependencies to be set. All you have to do is the following.

computed: {
   formattedText: function () {
      get: function () {
         return this.text.replace(‘ ‘, ‘’).reverse().toUpperCase()
      },
      set: function (value) {
         this.text = value;
      }
   }
}

How are computed properties different from watchers?

Both VueJS computed properties and watchers are able to update values based on data. While all computed properties are able to be written using watchers, it’s often more readable and efficient to use a computed property. Take the following example first written as a watcher and then as a computed property.

export {
   data () {
      return {
         name: ‘Matt’,
         age: 19,
         output: ‘’
      }
   },
   watch: {
      name: function (val) {
         this.output = this.name + ‘ is ‘ + this.age + ‘ years old.’
      },
      age: function (val) {
         this.output = this.name + ‘ is ‘ + this.age + ‘ years old.’
      }
   }
}
// Now as a computed property
export {
   data () {
      return {
         name: ‘Matt’,
         age: 19
      }
   },
   computed: {
      nameAndAge: function () {
         return this.name + ‘ is ‘ + this.age + ‘ years old.’
      }
   }
}

As you can see, the computed property is much simpler and less redundant while still offering the same responsiveness when the data changes.

But make sure you take some thought when you choose what to use for use case. A little bit of time spent considering the pros and cons before developing can save you a lot of time having to rewrite all your code down the line.

There you go.

You should have all of the basics to be able to use computed properties. Hopefully, this helps you condense your code and make it more readable and easy to understand.

If you want a more technical and more to the point usage of how exactly computed properties work. Check out the Vue documentation for more.

Let me know what tips you have!

One Response

  1. Łukasz January 26, 2020

Leave a Reply to Łukasz Cancel reply