Sobes.tech
Middle

setup() (executed before beforeCreate and created) onBeforeMount onMounted onBeforeUpdate onUpdated onBeforeUnmount onUnmounted Parent: setup Parent: beforeCreate Parent: created Parent: beforeMount Child: setup Child: beforeCreate Child: created Child: beforeMount Child: mounted Parent: mounted <template> <button @click="onClick"> {{ text }} </button> </template> <script lang="ts"> interface Props { text: string; } const props = defineProps<Props>(); interface Emit { myClick: [string]; } const emits = defineEmit<Emit>(); function onClick() { } </script> <template> <MyButton :text="Нажми на меня"></MyButton> </template>

sobes.tech AI

Answer from AI

In Vue 3, the component lifecycle with the Composition API begins with the invocation of setup(), which executes before the beforeCreate and created hooks in the Options API.

The order of hook calls for parent and child components:

  1. Parent: setup
  2. Parent: beforeCreate
  3. Parent: created
  4. Parent: beforeMount
  5. Child: setup
  6. Child: beforeCreate
  7. Child: created
  8. Child: beforeMount
  9. Child: mounted
  10. Parent: mounted

Lifecycle hooks of the Composition API:

  • onBeforeMount
  • onMounted
  • onBeforeUpdate
  • onUpdated
  • onBeforeUnmount
  • onUnmounted

Example of a component with the Composition API and TypeScript typing:

<template>
  <button @click="onClick">
    {{ text }}
  </button>
</template>

<script lang="ts" setup>
interface Props {
  text: string;
}
const props = defineProps<Props>();

interface Emit {
  myClick: [string];
}
const emit = defineEmits<Emit>();

function onClick() {
  emit('myClick', 'clicked');
}
</script>

In the parent component, you can use <MyButton :text="'Click me'" @myClick="handleClick" />.

Thus, setup is the place for initializing reactive data, functions, and subscriptions, while lifecycle hooks allow reacting to the component's lifecycle stages.

setup() (executed before beforeCreate and created)… - sobes.tech