1

In Vue.js docs I've found two ways of defining data so far: data: {} and data() { return; }.

data: {
    defaultLayout: 'default'
}

data() {
    return {
        defaultLayout: 'default'
    }
}

So far, I don't have any clue about third ways: data: () => ({}). How it makes differ from above two's.

data: () => ({
    defaultLayout: 'default'
})
tony19
  • 125,647
  • 18
  • 229
  • 307
S M Iftakhairul
  • 1,120
  • 2
  • 19
  • 42
  • 1
    The first one is an object, the second and third are functions that return objects. This isn't Vue specific, just basic JavaScript syntax. – jonrsharpe Apr 27 '19 at 10:11
  • Any difference between second and third? – S M Iftakhairul Apr 27 '19 at 10:12
  • 1
    https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable – jonrsharpe Apr 27 '19 at 10:14
  • 2
    The link you pointed to explains exactly the reason why in Vue.js `data` must be a function returning an object. It is in order to avoid passing an object reference which would be modified somewhere else. https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function – Rudy Apr 27 '19 at 10:30

3 Answers3

2

Inside an object literal,

data() {
    return {
        defaultLayout: 'default'
    }
}

is a shorthand for

data: function() {
    return {
        defaultLayout: 'default'
    }
}

which you can write with an arrow function:

data: () => ({
    defaultLayout: 'default'
})
Jean-Alphonse
  • 800
  • 4
  • 10
1

Arrow functions are shorthands for returning a value. If you write this code:

() => "aaa"

It returns "aaa" string. So there is a hidden return statement there. Keeping this in my if we look at:

data: () => ({
    defaultLayout: 'default'
})

Returns an object which has "defaultLayout" property. Let's look at your first code sample.

data() {
    return {
        defaultLayout: 'default'
    }
}

is equal to:

data: function() {
    return {
        defaultLayout: 'default'
    }
}

So second and third code samples are almost equal. There is just one difference, arrow functions have lexical "this".

Your first sample is a bad practice. You can read it about it here.

1

Only your second example is a valid one. Especially avoid using arrow function for data it sets thisto global so you'll be unable to reference anything from the vue instance.

data: () => ({
    someValue = 'default',
    defaultLayout: this.someValue //!!undefined!!!
})

The only valid one:

data() {
    return {
        defaultLayout: 'default'
    }
}
Hexodus
  • 12,361
  • 6
  • 53
  • 72