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.
Under the new Composition API, all of the variables that you previously defined in
data()
are just returned from yoursetup()
function as normal variables with reactive values. For example, a Vue 2.0 component that had a data function like so:becomes this
setup()
function in Vue 3:The
ref
helper wraps a non-object value for reactivity, andreactive
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 yoursetup()
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.