Alex S.
Alex S.

Reputation: 1214

What is an equivalent of `created()` in the Vue.js composition api?

Could you advise what is the equivalent of the created() in the new Vue composition API, which I'm using from within Vue2 like this:

import { reactive, toRefs } from '@vue/composition-api'

Upvotes: 61

Views: 43716

Answers (2)

Dan
Dan

Reputation: 63089

From the Composition API docs on Lifecycle Hooks:

Because setup is run around the beforeCreate and created lifecycle hooks, you do not need to explicitly define them. In other words, any code that would be written inside those hooks should be written directly in the setup function.

Anything you would have done in the created hook you can do in setup.

If you're coming from Vue 2, you can think of setup as a combination of created and data (and methods and watch, etc.) Combining all that into one function made it easier to define, import, and structure components in a variety of ways.

Upvotes: 135

Stefan Feuerhahn
Stefan Feuerhahn

Reputation: 1814

If your created() method is synchronous you can simply put the code in the <script setup> block.

You can also make the setup method asynchronous by adding a top-level await statement in the <script setup> block. But in this case you will have to use a <Suspense> boundary in the parent component tree as documented here.

If you have asynchronous code and you do not want to use <Suspense> then I would use the onBeforeMount() lifecycle hook instead.

Upvotes: 1

Related Questions