Why does the data property on a Vue component must be a function?
Winner Crespo
Posted on July 20, 2018
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'
}
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'
};
}
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.
Posted on July 20, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.