Search code examples
vue.jsvuejs2computed-properties

What exactly does computed properties in vuejs?


There are couple of questions related computed properties like the following

  1. "vuejs form computed property"

  2. "Computed properties in VueJs"

  3. "computed property in VueJS"

  4. "Use computed property in data in Vuejs"

They are asking about specific error or logic. There are lot of websites that are explaining about vuejs related concepts. I read about computed properties on vuejs official website. When we do complex calculations or want to avoid to write more logic in our html template then we use computed properties.

But could not get any solid understanding about computed properties, when it calls, how it calls, what exactly do?


Solution

  • TL;DR: Computed properties are getters/setters in Vue.


    When defined in the shorthand form, they are getters:

    computed: {
      someComputed() {
        return `${this.foo} ${this.bar}`;
      }
    }
    

    is equivalent with

    computed: {
      someComputed: {
        get: function() {
          return `${this.foo} ${this.bar}`;
        }
      }
    }
    

    which can also have a setter:

    computed: {
      someComputed: {
        get: function() {
          return `${this.foo} ${this.bar}`;
        }
        set: function(fooBar) {
          const fooBarArr = fooBar.split(' ');
          this.foo = fooBarArr[0];
          this.bar = fooBarArr[1];
        }
      }
    }
    

    In short, Vue computed properties allow you to bind an instance property to

    • a getter: function run when you look up that property; usage:
    this.someComputed // returns the computed current value, running the getter.
    
    • a setter: function run when you attempt to assign that property; usage:
    this.someComputed = value; // sets the computed current value, running the setter.
    

    Read more on getters and setters in Javascript.

    And here's the documentation on Vue computed properties.