1

When I started with Vue.js I read about a case where you return a data property with return and sometimes without. I cannot find that article anymore that's why I'm asking here.

That's how I use it today

 data: function () {
      return {
        myData : "data"
      }
    },

But that's how I see it in documentation very often - don't know the difference anymore:

 data: {
    myData: "data"
  },
1
  • I was wondering about the same thing, but didn't bother to research it. Thanks for asking :) Commented Jun 13, 2017 at 17:58

1 Answer 1

3

https://vuejs.org/2016/02/06/common-gotchas/#Why-does-data-need-to-be-a-function

Why does data need to be a function?

In the basic examples, we declare the data directly as a plain object. This is because we are creating only a single instance with new Vue(). However, when defining a component, data must be declared as a function that returns the initial data object. Why? Because there will be many instances created using the same definition. If we still use a plain object for data, that same object will be shared by reference across all instance created! By providing a data function, every time a new instance is created, we can simply call it to return a fresh copy of the initial 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.