0

I see computed properties and methods in the Vue docs like this:

export default {
  computed: {
    foo: function() { return 'foo'; }
  },
  methods: {
    bar: function(x) { return 'bar ' + x; }
  }
}

However, I've also seen the function keyword omitted. Is this allowed? Are there any drawbacks?

export default {
  computed: {
    foo() { return 'foo'; }
  },
  methods: {
    bar(x) { return 'bar ' + x; }
  }
}
Muhammad Rehan Saeed
  • 31,909
  • 32
  • 185
  • 290
  • The only difference between them is that the shorthand function cannot be used as a constructor function with `new` operator ([Constructor behaving differently using ES6 shorthand notation](https://stackoverflow.com/q/41193117)). But, this is inside Vue object, so it is irrelevant here. You can use them interchangeably. – adiga Jun 05 '20 at 17:54

1 Answers1

1

Yes, this is allowed, starting from ES6.

From the MDN

Starting with ECMAScript 2015, a shorter syntax for method definitions on objects initializers is introduced. It is a shorthand for a function assigned to the method's name.

const obj = {
  foo() {
    return 'bar';
  }
};

console.log(obj.foo());
// expected output: "bar"

Drawbacks:

  • This syntax is not supported by IE11
  • You probably need a transpiler, like Babel to use this syntax in non-supported environments
Kostas Minaidis
  • 2,819
  • 1
  • 14
  • 22