data() function
The data function returns a fresh object of state for every component instance.
In this page:
Syntax
export default {
data() {
return {
property: value
};
}
}
data() function
In the Options API, data must be a function returning an object so each component instance gets its own copy. Properties returned become reactive and are accessible on this.
Properties added later are not reactive unless declared up front, so declare every field you need.
Note:
Declare all state fields in data, even if empty, so they are reactive.
Example: data() function
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<counter-box></counter-box>
<counter-box></counter-box>
</div>
<script>
const app = Vue.createApp({});
app.component("counter-box", {
data() { return { n: 0 }; },
template: '<button @click="n++">clicks: {{ n }}</button>',
});
app.mount("#app");
const [a, b] = document.querySelectorAll("button");
a.click(); a.click(); b.click();
Vue.nextTick(() => console.log("independent state:", a.textContent, "|", b.textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: clicks: 2clicks: 1
console: independent state: clicks: 2 | clicks: 1
-->
Live Example
Related Topics
Common Mistakes
- Making data a plain object in components
- Adding new properties later and expecting reactivity
- Using arrow functions that break this
Chapter Summary
- data returns an object
- Each instance gets its own state
- Declare all fields up front
- Properties appear on this
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: