Using data()
data() is typically used in Vue's Options API to define component reactive data. It is suitable for developers familiar with Vue 2 or when migrating legacy projects to Vue 3 to maintain code consistency.
Example:
javascriptexport default { data() { return { count: 0 }; }, methods: { increment() { this.count++; } } }
In this example, count is a reactive data property that can be directly used in templates or other compositional logic.
Using setup()
setup() is a new concept introduced in Vue 3, belonging to the core of the Composition API, used for defining component reactive state, computed properties, methods, etc. setup() executes before the component instance is created, so it does not rely on the this context, making type inference easier and highly suitable for TypeScript development.
Example:
javascriptimport { ref, computed } from 'vue'; export default { setup() { const count = ref(0); const doubleCount = computed(() => count.value * 2); function increment() { count.value++; } // Return values are exposed to the template return { count, doubleCount, increment }; } }
In this example, we use reactive references ref and computed properties computed to define state and derived computations. All logic is included within setup(), and since they are function-based, they are easier to reuse and test.
Summary
- Use
data(): When using the Options API or when the project needs to maintain consistency with Vue 2 code. - Use
setup(): When leveraging the advantages of Vue 3's Composition API, such as better type support, clearer logic reuse, and organization.
The choice depends on your project requirements and familiarity with Vue. In practice, you can even mix both APIs within the same project based on specific needs.