Computed in Vue 3

Computed in Vue 3

Vue.js has six options which are data, props, computed, methods, watch and emits. Among them, we are going to discuss about computed in vue 3 options. We can use this option while creating the components. It will ease the complex component creations and logics. We can write or compose a component logics using computed.

In Vue.js 2, we will use computed as a property of SFC’s. But Computed in Vue 3 moved to separate module. So we have to import from vue. Let’s take a deep dive!.

Note that, we are using Single file Components SFC’s in examples. So you can refer more about SFC’s from Single File Components Vue 3

Computed in Vue 3

Computed in Vue 3

There are two basic reasons to use computed property.

  1. Behavior Dependency on reactive variables.
  2. To move complex template logics on reactive variables.

Behavior Dependency

Every component has unique core logics, in such a way that it will fulfill it’s requirements. While organizing the component logic, sometimes we need one behavior that depends on the other behaviors. We can handle this situation using computed properties. Computed has two properties namely get and set.

get function

The computed method takes a getter function, and it will return the reactive immutable ref object. There are two syntax to create get function,

Note that, here the function is given as an argument of computed method directly.

const fullName = computed(() => {
      return props.firstName + " " + props.lastName;
 });

Alternatively, we can assign the function on get property as follows,

const fullName = computed({
      get: () => {
        return props.firstName + " " + props.lastName;
      },
 });

Now we are going to see the full example for computed getter function. The important point here is that the fullName depends on first name and last name. The fullName takes a getter function and return reactive ref object. We will return this fullName object from the setup hook.

Example

set function

We have one more set function to create a writable ref object. We won’t use setter function mostly in computed method. It has only one syntax as follows,

const counterResult = computed({
      set: (val) => {
        counter.value = counter.value + val
      },
 });
// To increment
counterResult = 1 // It will increment by one

Now we are going to see the full example.

Example

  1. We are using two props initialNumber and incrementBy.
  2. The counter ref created from initialNumber.
  3. counterResult having get/set functions where get is used to return current counter value.
  4. set function takes an argument and return the increment result
  5. In Template button click, we are setting computed value as follows
    counterResult = incrementBy

To move complex template logics

In Vue.js, we can write expressions in the template. Its the special feature and very convenient for simple operation. Meanwhile when the logic increases, we have to write lot of expressions inside template. It will reduce the readability of template and makes harder to understand. So we can use computed to handle such situations. Note that, here we have to move template expressions logics into computed.

In the below example, the message is reversed inside template expression. For more information, you can refer Template Expressions

<template>
  <div>
    <div>Message : {{ message }}</div>
    <div>Reversed Message : {{ message.split("").reverse().join("") }}</div>
  </div>
</template>

In this case, we are using the JavaScript expressions inside template. At this point it is okay. But when the template logic increases, it makes hard to understand. So we can move this logic as follows,

<div>Reversed Message : {{ reversedMessage }}</div>

const reversedMessage = computed(() => {
      return props.message.split("").reverse().join("");
});

Now, the template logic is implemented in computed.

Full Example

Computed Caching

Instead of computed, we can achieve the above logic by using method option also.

methods: {
    reversedMessage : () => {
      return this.message.split("").reverse().join("");
    }
  },

In the above example, we are using method instead of computed. Indeed, the end results are same. Then what’s the difference ? which one is preferable ?. The difference is, computed are cached by nature based on their reactive dependencies. The computed logic re-executed only when it’s reactive variable changes. However The results are cached and immediately return the previously computed value.

Note that, whenever re-render happens, methods will always run the functions irrespective of it’s reactive dependency changes. So the use case depends on component creator. If we want to cache the result we can go for computed. If we want to run the function for every re-render, always we have to use methods.

Conclusion

Among Vue.js six data options, we have learned something about computed property. Some important revisions are,

  • We can use computed for Behavior Dependency and to move complex expression logic from template
  • It has get, set property. If we give single function, then it will be a get function by default.
  • Computed are cached by nature. It won’t always run the function when re-render happens. The computed logic re-executed only when it’s reactive variable changes.

Leave a Reply

%d bloggers like this: