Hello everyone and thanks in advance for your help.
I am new to VueJS and was asked to work with a big codebase that uses the OptionAPI of VueJS. This code was written before Vue3 was release. However, it seems like the programmers of this had been already using features of the CompositionAPI such as the setup()
hook alongside with the data()
method to declare the state.
My problem is, I can’t understand the difference between the setup()
hook and the data()
function in terms of functionalities provided to the component. In many places of this code base, components use both functions to declare their properties / functions that will be used in the code.
What is the difference between declaring a property inside data()
and one inside setup()
? Is it simply the sign of bad programming practice, or could it have been done for a specific reason ?
For instance, here is the most naive example. In this case, is there any reason why using the setup()
method ?
<script>
import { ref } from'vue'
export default {
data() {
return {
count: 0
}
},
setup() {
const tmp = ref(0)
// expose to template and other options API hooks
return {
tmp
}
},
mounted() {
console.log(this.count) // 0
}
}
</script>
<template>
<div>
Control with Option API: <button @click="count++">{{ count }} and {{tmp}}</button>
<p></p>
Control with Composition API: <button @click="tmp++">{{ count }} and {{tmp}}</button>
</div>
</template>
Thanks for your precious help.
2
Answers
maybe they want to emphasize data . the difference is that anything
data()
returns will be reacted whilesetup()
is a general purpose pattern it can return anything (methods, data, mixins, components…)basically your example is equivalent it’s just a matter of whether you like it or not
If both
data
andsetup
as used in a component, the most likely reason for that may be thatsetup
acts like a modern alternative formixins
:playground
Old mixins have many problems with type support, overlapping, and other unexpected things. Using composition-style mixins in
setup
is much more clear way to express what you want, get better typings, and provide better code quality all at once.Data and Setup don’t really have differences other than:
async
(must be used with<Suspense>
)And that’s it (comment if I’ve missed something important)