When working with Vue, you might find yourself asking the question, “Why must data
be a function that returns an object, instead of just an object?”
Consider the following example:
<template>
<a v-on:click="counter = counter + 1">{{counter}}</a>
</template>
<script>
export default {
data: function() {
return {
counter: 0
}
}
}
</script>
You may have also noticed that in some places, data
is not a function, such as in the App component in various examples.
The reason for this is that when a component is used multiple times, if data
is a regular object rather than a function, like this:
data: {
counter: 0
}
then, due to the nature of JavaScript, every instance of the component will share this property.
In most cases, this is not the behavior you desire. Instead, you should use a function to return an object, like this:
data: function() {
return {
counter: 0
}
}
This may seem counterintuitive at first, but once you understand the reasoning behind it and realize its potential to cause harm and introduce bugs to your application, you will always remember to use a function for data
.