Reputation: 1263
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
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:
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