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?
<script>
export default {
data() {
return {
count: 0,
message: "Hello",
isOpen: false
}
}
}
</script>Now:
countmessageisOpen
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:
data: {
count: 0
}Correct:
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:
this.count++
this.isOpen = trueautomatically trigger a UI update.
Where is data from data() used?
In the template:
<p>{{ count }}</p>In methods:
methods: {
increment() {
this.count++
}
}In computed properties:
computed: {
upper() {
return this.message.toUpperCase()
}
}In watchers:
watch: {
count(newVal) {
console.log('count changed:', newVal)
}
}Example of a full Options API component
<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.someValuetriggers a UI update
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.