← Back to Vue.js Course | Chapter 3: Reactivity | Lesson 1 of 7

data() function

The data function returns a fresh object of state for every component instance.

In this page:

  1. data() function
Syntax
markup
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

markup
<!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
  1. Making data a plain object in components
  2. Adding new properties later and expecting reactivity
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.