0

I know vue expects data to be an function returning an object, so:

data () {
  return {}
}

works, but this doesn't work:

data: () => {

}

Why doesn't it work though? aren't' they both the same functions returning an object

hidar
  • 5,449
  • 15
  • 46
  • 70
  • Yes, it won't work. Read up about fat arrows and how to use them. – Ohgodwhy Mar 22 '18 at 16:30
  • Also, https://stackoverflow.com/questions/42971081/use-arrow-function-in-vue-computed-does-not-work and there are more... please do some research before asking question in future... – Bhojendra Rauniyar Mar 22 '18 at 16:36

1 Answers1

5

That's because when you use { in arrow functions, you begin a block, not an object.

The following would work:

data: () => ({

})

Notice the ( and ). From MDN/Arrow Functions/Syntax:

Syntax - Advanced Syntax

// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})

But, anyway, don't use these in Vue. From the API Docs:

Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }}). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.myProp will be undefined.


Update: > **Per comment:** But even with the recommended way you still can't use `this` so what is the point?

You can. Consider props. You may want to mutate a prop's value (using v-model), which is not recommended. To achieve that functionality, the best practice is to create a internal property (e.g. internalStuff) in your data and initialize with the props value:

Vue.component('my-component', {
  props: ['stuff'],
  data() {
    return {internalStuff: this.stuff}; // this works fine, wouldn't with arrow functions
  },
  template: `<input type="text" v-model="internalStuff">`
}
tony19
  • 125,647
  • 18
  • 229
  • 307
acdcjunior
  • 132,397
  • 37
  • 331
  • 304