/

Why Data Must Be a Function in Vue

Why Data Must Be a Function in Vue

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
<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:

1
2
3
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:

1
2
3
4
5
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.

tags: [“Vue”, “data”, “function”, “object”, “component”]