Templates in VueJS are quite powerful. You can even compute stuff using Vue template syntax. However, putting too much calculation logic in templates is not a good design. Vue 3 Computed Properties can handle complex computation logic with minimum overhead while rendering the DOM.

In this post, we will look at computed properties in VueJS for both options API and composition API.

1 – What is Computed Property in Vue 3?

Computed Property in Vue3 is used to declaratively describe a value that is dependent on other values. This feature of VueJS allows for transformations or computations based on our data. We can reuse the result of these computations and transformations in our DOM template.

Computed properties remove the need for complex in-template expressions. Instead, we can use computed properties in our template. Vue automatically updates the DOM when any value on which the computed value depends changes.

2 – What is the Difference Between Computed Property and Methods in VueJS?

Computed Property and Methods in VueJS have completely different use-cases. Methods do not keep track when the values within the function change. This is the reason that a function has to run every time to derive the result. On the other hand, computed properties keep track of changes in the value. They don’t need to run every time to check. Also, for this reason, computed properties are cached.

3 – When should you use computed property in VueJS?

We should use computed values in VueJS when we have a requirement to perform complex calculations. Doing a complex calculation every time is costly. Since computed property provides caching and is only triggered when there is a change to the data used in the computed value, it is far more efficient as compared to a function.

4 – Is Computed Property Reactive in Vue?

A computed property’s dependencies are reactive values that are used to determine the value of the computed property. If none of these dependencies change, the cached value will be returned. If the reactive values change, it will trigger the computed property to re-compute the modified value.

5 – Vue 3 Computed Properties with Composition API

It is now time to look at some examples for Vue 3 Computed Properties. We will first start with Composition API and then proceed with Options API.

In case you are not aware of these terms, do check out this detailed post on VueJS Options API vs Composition API.

5.1 – Read-only Computed Property

To declare a computed property in Vue 3, we need to use the computed() function.

See below example:

import { reactive, computed } from 'vue'

const product = reactive({
  items: ['Macbook', 'IPhone13', 'Playstation5'],
})

const hasItems = computed(() => {
  return product.items.length > 0 ? 'Yes' : 'No'
})

const itemsLength = computed(() => {
  return product.items.length
})

As you can see, we have a list of items. Based on them, we declare two computed properties hasItems and itemsLength.

We can use the computed values in our template.

<template>
  <h2>Non-Computed Approach</h2>
  <h3>Items Available: {{ product.items.length > 0 ? 'Yes' : 'No' }}</h3>
  <h3>Total Items: {{ product.items.length }}</h3>
  <h2>Computed Approach</h2>
  <h3>Items Available: {{ hasItems }}</h3>
  <h3>Total Items: {{ itemsLength }}</h3>
</template>

In the non-computed approach, we write expressions in the template. Every time VueJS renders the template, it will run those expressions and calculate the values.

However, by using the computed properties approach, we can directly refer to the computed properties hasItems and itemsLength using the mustache syntax. Since computed properties in VueJS are cached, there is no need for calculating unless there is a change in the items array.

Vue 3 computed properties are reactive. Basically, the dependencies are reactive. So the execution of the below function will lead to a recalculation of the computed properties. You can read more Vue 3 Reactivity in Composition API.

function addItem() {
  product.items.push('Xbox Series X')
}

Basically, we are pushing a new item to the array. This will cause a change to the itemsLength property.

5.2 – Writable Computed Property

By default, computed properties in VueJS are read-only. We cannot directly assign a new value to a computed property.

However, VueJS also supports writable computed property. In such a property, we can provide both getter and setter methods.

See below example:

const companyName = ref('ABC')
const division = ref('Electronics')

const fullCompanyName = computed({
  get() {
    return companyName.value + ' ' + division.value
  },
  set(newValue) {
    ;[companyName.value, division.value] = newValue.split(' ')
  },
})

function changeCompanyName() {
  fullCompanyName.value = 'XYZ Electronics'
}

When we invoke the changeCompanyName() function, it will trigger the setter method of the computed property fullCompanyName. The new value is split and the companyName and division values get updated.

Note that getters for computed properties should not have any side-effects. We should not try to make async requests within the getter methods.

You can play around with the complete example on Stackblitz.

6 – Vue 3 Computed Properties with Options API

In VueJS Options API approach, computed properties are declared using the computed block. Let us first look at the read-only approach.

6.1 – Read-only Computed Property

Below is an example of the read-only computed property in VueJS.

<script>
export default {
  // Properties returned from data() becomes reactive state
  // and will be exposed on `this`.
  data() {
    return {
      product: {
        items: ['Macbook', 'IPhone13', 'Playstation5'],
      },
      companyName: 'ABC',
      division: 'Electronics',
    };
  },
  // Methods are functions that mutate state and trigger updates.
  // They can be bound as event listeners in templates.
  methods: {
    addItem() {
      this.product.items.push('Xbox Series X');
    },
  },
  computed: {
    hasItems() {
      return this.product.items.length > 0 ? 'Yes' : 'No';
    },
    itemsLength() {
      return this.product.items.length;
    },
  },
};
</script>

As you can see, we have the same items array. Within the computed property of the default object, we declare two methods hasItems() and itemsLength(). Basically, these are computed properties.

We use them in the template in a similar way to composition API.

<template>
  <h2>Non-Computed Approach</h2>
  <h3>Items Available: {{ product.items.length > 0 ? 'Yes' : 'No' }}</h3>
  <h3>Total Items: {{ product.items.length }}</h3>
  <h2>Computed Approach</h2>
  <h3>Items Available: {{ hasItems }}</h3>
  <h3>Total Items: {{ itemsLength }}</h3>
</template>

6.2 – Writable Computed Property

In Options API, we can also have a writable computed property. Basically, we have to declare getter and setter methods for property.

See below example:

methods: {
    changeCompanyName() {
      this.fullCompanyName = 'XYZ Electronics';
    },
},
computed: {
    fullCompanyName: {
      get() {
        return this.companyName + ' ' + this.division;
      },
      set(newValue) {
        [this.companyName, this.division] = newValue.split(' ');
      },
    },
},

Syntactically, this is almost similar to the approach for Composition API.

You can play around with the complete example on Stackblitz.

Conclusion

Computed properties in Vue 3 are absolutely important when writing complex templates. They work both with Options API and Composition API. In this post, we looked at both the options.

Want to learn more about VueJS? Check out this detailed post on conditional rendering in VueJS.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: VueJS

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *