2

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'
})
4
  • 2
    The first one is an object, the second and third are functions that return objects. This isn't Vue specific, just basic JavaScript syntax. Commented Apr 27, 2019 at 10:11
  • Any difference between second and third? Commented Apr 27, 2019 at 10:12
  • 1
    stackoverflow.com/questions/34361379/… Commented Apr 27, 2019 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. vuejs.org/v2/guide/components.html#data-Must-Be-a-Function Commented Apr 27, 2019 at 10:30

3 Answers 3

2

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'
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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'
})

1 Comment

I am sorry, but regular function != arrow function where scope of keyword this differs, and in Vue it may be crucial in certain life cycle stages: v2.vuejs.org/v2/api/#data ; Related: stackoverflow.com/questions/48980865/…
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.