DEV Community

Cover image for Why does the data property on a Vue component must be a function?
Winner Crespo
Winner Crespo

Posted on • Originally published at winnercrespo.com on

Why does the data property on a Vue component must be a function?

If you don’t get familiar with the basic rules of a framework (programming language, tool, etc) when starting to use it, things won’t work as expected, since it wasn’t conceived that way.

While using Vue for the first time, I made this by mistake:

data: {
  message: 'Some Message'
}
Enter fullscreen mode Exit fullscreen mode

then, I got the following warning message:

[Vue warn]: The “data” option should be a function that returns a per-instance value in component definitions.

What you should do instead is:

data: function() {
  return {
    message: 'Some Message'
  };
}
Enter fullscreen mode Exit fullscreen mode

So, the reason why Vue forces the data property to be a function is that each instance of a component should have its own data object. If we don’t do that, all instances will be sharing the same object and every time we change something, it will be reflected in all instances.

Check out what the Vue’s documentation says about it and a quick live example.

I hope this helps.

Top comments (0)