Sobes.tech
Middle

// comp.vue <template> <ul v-if="products != null"> <li v-for="(pr, i) in products">{{pr}}</li> </ul> </template> <script> import {getProducts} from ""; import {ref} from "vue"; const products = ref(null); onMounted(() => { getProducts().then(result => products.value = result) }) </script> setup() (executes 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> <div> <slot name=""></slot> </div> </template>

sobes.tech AI

Answer from AI

The provided Vue 3 code uses the Composition API with the setup function and lifecycle hooks.

  • setup() is called before beforeCreate and created, and initializes reactive data.
  • onMounted() is called after the component is mounted, where an asynchronous call to getProducts() occurs and the reactive variable products is updated.

The order of lifecycle hook calls in nested 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

This means that the child component is fully initialized and mounted before the parent component completes mounting.

Example of using hooks in the Composition API:

<script setup>
import { ref, onMounted } from 'vue';

const products = ref(null);

onMounted(async () => {
  products.value = await getProducts();
});
</script>

<template>
  <ul v-if="products">
    <li v-for="(pr, i) in products" :key="i">{{ pr }}</li>
  </ul>
</template>

Thus, setup is the place for initializing reactive data and registering hooks, while the other lifecycle hooks allow managing the component's behavior at different stages of its existence.

// comp.vue <template> <ul v-if="products != null">… - sobes.tech