1

I'm wondering what is the different between the following format, and is there a different effect:

data: function() {
  return {
    name: 'John',
    phone: 12345
  }
}

Here's the other format:

data: {
  name: 'John',
  phone: 12345
}
1

1 Answer 1

6

Using Vue you might surely asked yourself the question “why must data be a function that returns an object, and not just an object?”

Especially considering that in some places, data is not a function, as you most probably see in the App component in several examples.

The explanation is that when the component is used multiple times, if it’s not a function, but a regular object, like this:

data: { name: 'John', phone: 12345 }

then because of how JavaScript works, every single instance of the component will share this property. This is not what you want in 99.9% of the cases, and instead you must do:

data: function() { return { name: 'John', phone: 12345 } }

It might be non-intuitive at first, but once you accept this explanation and learn that it’s kind of harmful to your application, and a possible source of bugs, you’ll remember to always use a function for data.

Sign up to request clarification or add additional context in comments.

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.