Vue, why data must be functions

With Vue, you will definitely ask yourself a question: "Why must the data be a function that returns an object, not just an object?"

When using Vue, you will definitely ask yourself a question: "Why do you have todataIs it a function that returns an object, not just an object? "

<template>
  <a v-on:click="counter = counter + 1">{{counter}}</a>
</template>

<script> export default { data: function() { return { counter: 0 } } } </script>

Especially in some places,dataYesIs notA feature, as you are most likely to see in the App component in a few examples.

The explanation is that when the component is used multiple times, if it is not a function, but a regular object, it looks like this:

data: {
  counter: 0
}

Then because of how JavaScript works,Every instance of the component will share this property.

In 99.9% of cases, this is not what you want, but the following must be done:

data: function() {
  return {
    counter: 0
  }
}

It may not be intuitive at first glance, but once you accept this explanation and understand that it is harmful to your application and may be the source of the error, you will always remember to use a function to process the data.

Download mine for freeVue manual


More vue tutorials: