Reading the composition api documentation for Vue 3, I didn't quite understand how the new Composition API works. Could you please explain where the data()
function has gone? And if it is no longer used what to use instead?
Updated 23.10.2021: The documentation in the link has been updated and expanded to include a mention of the data()
in the Composition API introduction, so this question is now deprecated.
Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It is an umbrella term that covers the following APIs: Reactivity API, e.g. ref() and reactive() , that allows us to directly create reactive state, computed state, and watchers.
It still supports Options API at its core. It is also possible to use both methods together in a single Vue component.
Under the new Composition API, all of the variables that you previously defined in data()
are just returned from your setup()
function as normal variables with reactive values. For example, a Vue 2.0 component that had a data function like so:
data() {
return {
foo: 1,
bar: { name: "hi" }
}
}
becomes this setup()
function in Vue 3:
setup() {
const foo = ref(1);
const bar = reactive({ name: "hi" });
return { foo, bar }
}
The ref
helper wraps a non-object value for reactivity, and reactive
wraps an object. This is exposing the underlying principles of Vue more clearly than the old way, where the wrapping happened "magically" behind the scenes, but will behave the same otherwise. What I like about it personally is that your setup()
function can build up your object on the go while keeping related things together, allowing it to tell a cohesive story and not require jumping around to different sections.
The composition is the new feature comes with Vue 3 and as a plugin for Vue 2, it doesn't replace the old option api but they could be used together in the same component.
The composition api compared to option api :
setup
function which is executed before the component is created, once the props are resolved, and serves as the entry point for composition API's.ref
or reactive
propertieswatch(...,()=>{...})
or computed(()=>{...})
setup
option used instead of created hook and it has as parameters the props
and context
mounted
could be used as onMounted(()=>{...})
, learn more
With script setup
syntax you could declare your reactive data using ref
, reactive
and computed
...
<script setup >
import { ref, reactive, computed } from 'vue'
const isActive = ref(false)
const user = reactive({ firstName: 'John', lastName: 'Doe', age: 25 })
const fullName = computed(() => user.firstName + ' ' + user.lastName)
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With