Skip to content

How to read/write to computed properties?

reading and writing to computed properties in vuejs

We’ll create a computed property if we want to re-render the text/value based on the property change. We will use the computed property in the template section of the vue file(s).

Do you know you can use the computed property in any method to get the value and you could also write data to the computed property? If you already knew it, you can skip this post.

In this post, we’ll see how to read and write to computed properties.

Reading computed property in another computed property

Apart from using the computed properties in the Vue templates, we can also use the computed properties in any methods, watchers or in other computed properties.

Let’s have an example.

<template>
    <div>
        {{ careerPoints }}
    </div>
</template>
<script>
    export default {
        data() {
            return {
                firstName: "Karthik",
                lastName: "Chintala"
            };
        },
        computed: {
            fullName () {
                return this.firstName + ' ' + this.lastName;
            }
            careerPoints() {
              if (this.fullName === "Lebron James") {
                return "Total career points: 33,692";
              }
              return "";
            }
        }
    }
</script>

In the above example, we are using the fullName computed property in careerPoints computed property to display career points.

If the fullName is LeBron James, then we’ll display his total career points in the NBA, which is 33,692 (as on writing this post).

Writing to computed properties

In the above example, we can read the fullName computed property. But, we cannot write to the fullName.

If we try to assign a value to the fullName, we’d see a warning as there’s no setter in fullName computed property yet.

Let’s add a setter to the fullName computed property. Here’s how it looks after adding getter and setters.

fullName: {
      get: function() {
        return this.firstName + " " + this.lastName;
      },
      set: function(value) {
        let names = value.split(" ");
        this.firstName = names[0];
        this.lastName = names[names.length - 1];
      }
    }

So, our fullName computed setter will receive the value as “Lebron James” and sets the first name and last name by splitting the string with space.

Now we have setter defined on the fullName computed property, let’s add a button on the page which will set the fullName to “Lebron James”.

<template>
    <button @click="setFullNameToLJ()">Set full name to Lebron James</button>
</template>
<script>
    export default {
        methods: {
            setFullNameToLJ() {
              this.fullName = "Lebron James";
            }
        }
    }
</script>

If we click the button, we set the `fullName` computed property to Lebron James.

Note that we must tweak the logic of the fullName setter to work properly and to handle the edge cases of the fullName setter. Say, if the assigned value does not have a space between the first name and last name.

Here’s the complete source code of reading and writing to the computed properties.

<template>
  <div>
    First Name:
    <input type="text" v-model="firstName">
    <br>Last name:
    <input type="text" v-model="lastName">
    <br>
    Full Name: {{ fullName }}
    <br>
    <br>
    <button @click="setFullNameToLJ()">Set full name to Lebron James</button>
    <br>
    <br>
    <div>{{ careerPoints }}</div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      firstName: "Karthik",
      lastName: "Chintala"
    };
  },
  methods: {
    setFullNameToLJ() {
      this.fullName = "Lebron James";
    }
  },
  computed: {
    fullName: {
      get: function() {
        return this.firstName + " " + this.lastName;
      },
      set: function(value) {
        let names = value.split(" ");
        this.firstName = names[0];
        this.lastName = names[names.length - 1];
      }
    },
    careerPoints() {
      if (this.fullName === "Lebron James") {
        return "Total career points: 33,692";
      }
      return "";
    }
  }
};
</script>

Here’s the demo of the above code in code sandbox.

Conclusion

It’s interesting to find out that we can set some value to the computed properties and also we can access the computed properties in any methods, watchers, or other computed properties.

Last year, I wrote a post about how computed properties work under the hood. You can check it out if you are interested.

Any thoughts? Please let me know in the comments section.

Leave a Reply

Your email address will not be published.