Rain Man
Rain Man

Reputation: 1263

when to use data() and when to use setup() in vue3?

I am still new to Vue and when I was using vue 2, I always used this:

data() {
        return {
           ....
        }
}
methods: {
  ....
}

but now I see a lot of docs with

setup() {
 const .....
 return { ... }

}

are these essentially the same? when would be a use case for data() vs setup()?

Upvotes: 16

Views: 13675

Answers (1)

Oleg Naumov
Oleg Naumov

Reputation: 587

In Vue.js 2 you have been using the so-called Options API. Vue.js 3 comes with the Composition API that can be used instead of the Options API.

Both ways are essentially the same and you can go with either one. However, you should understand the difference (for example, this doesn't refer to the component in the setup() method and you shouldn't use it).

The Composition API approach is better for various reasons explained in detail in the official FAQ. In short, it provides:

  • Better Logic Reuse
  • More Flexible Code Organization
  • Better Type Inference
  • Smaller Production Bundle and Less Overhead

You can still use the Options API, it won't be deprecated and is perfectly suitable for smaller projects.

I highly suggest reading this article about it: Why I Love Vue 3's Composition API.

Upvotes: 7

Related Questions