Skip to main content

What is data() in Options API?

data() in the Options API is a function that returns an object with the component's local reactive state. All properties that data() returns become available in the template and via this inside methods, computed, and watch.

data() is where reactive component data is stored in the Options API.


What does data() look like?

javascript
<script> export default { data() { return { count: 0, message: "Hello", isOpen: false } } } </script>

Now:

  • count
  • message
  • isOpen

are the component's state.


Why does it have to be a function?

Because every component must have its own copy of the state.

If data were an object, all instances of the component would share the same state (which is bad).

Example:

Wrong:

javascript
data: { count: 0 }

Correct:

javascript
data() { return { count: 0 } }

Each call to data() -> a new copy of the object.


How Vue makes data reactive

Vue "wraps" all properties of the object returned by data() in reactivity.

That is, expressions like:

javascript
this.count++ this.isOpen = true

automatically trigger a UI update.


Where is data from data() used?

In the template:

javascript
<p>{{ count }}</p>

In methods:

javascript
methods: { increment() { this.count++ } }

In computed properties:

javascript
computed: { upper() { return this.message.toUpperCase() } }

In watchers:

javascript
watch: { count(newVal) { console.log('count changed:', newVal) } }

Example of a full Options API component

javascript
<script> export default { data() { return { count: 0, name: '' } }, methods: { increment() { this.count++ } } } </script> <template> <div> <input v-model="name" placeholder="Enter your name" /> <button @click="increment">Count: {{ count }}</button> </div> </template>

Summary (in short)

data() is a function that returns an object with the component's reactive data in the Options API.

  • it is required for local state
  • it must return an object
  • each component gets its own instance of that object
  • any change to this.someValue triggers a UI update

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.