52

I'm curious both of this data function, is there any difference between this two.

I usually saw is

data () {
  return {
    obj
  }
}

And ES6 fat arrow (=>) which I typically used

data:()=>({
  obj
})
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
BGTabulation BGTabulate
  • 1,677
  • 3
  • 16
  • 39
  • 1
    Possible duplicate of [ECMAScript6 arrow function that returns an object](https://stackoverflow.com/questions/28770415/ecmascript6-arrow-function-that-returns-an-object) – Andy Ray Feb 26 '18 at 03:06
  • Same thing, you just cant use the arrow way in vuejs for the data func since it doesnt bind this to the right thing inside the vue Obj – WilomGfx Feb 26 '18 at 03:08

2 Answers2

72

No difference in your specific example, but there is a very important difference between those two notations, specially when it comes to Vue.js: the this won't reflect the vue instance in arrow functions.

So if you ever have something like:

export default {
    props: ['stuffProp'],
    data: () => ({
      myData: 'someData',
      myStuff: this.stuffProp
    })
}

It won't work as you expect. The this.stuffProp won't get the stuffProp prop's value (see below for more on the reason why).

Fix

Change the arrow function to, either (ES6/EcmaScript 2015 notation):

export default {
    props: ['stuffProp'],
    data() {                                   // <== changed this line
      return {
        myData: 'someData',
        myStuff: this.stuffProp
      }
    }
}

Or to (regular, ES5 and before, notation):

export default {
    props: ['stuffProp'],
    data: function() {                           // <== changed this line
     return {
        myData: 'someData',
        myStuff: this.stuffProp
      }
    }
}

Reason

Don't use arrow functions (() => {}) when declaring Vue methods. They pick up the this from the current scope (possibly window), and will not reflect the Vue instance.

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.

tony19
  • 125,647
  • 18
  • 229
  • 307
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • 7
    FYI, a component's `data` function receives the instance as the first argument so you can use `data: vm => ({ myStuff: vm.stuffProp })` – Phil Aug 26 '20 at 01:35
0

It has something to do with ES5 or ES6 syntax, If you have used arrow functions ()=> in your previous scripts it is safe to use the following codes.

// tested and this.myData can be accessed in the component
data: () => { return {
    myData: 'someData',
    myStuff: this.stuffProp
} }

// this also works
data: () => ({
    myData: 'someData',
    myStuff: this.stuffProp
})
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
grit
  • 83
  • 4