Vue3 Wait till Child Component is Mounted

Viewed 749

I want to wait for a child component to mount before rendering a tooltip. While waiting, I will have a placeholder to display to the user.

An example component would be:

<template>
   <div v-if="!mounted">Loading...</div>
   <child-component></child-component>
</template>
<script>
export default defineComponent({
   setup() {
       const mounted = ref(false);       

       return { 
           mounted
       } 
   }
});
</script>

After doing research, it looks like Vue2 supports life-cycle hooks on the components, which would change the above code to:

<template>
   <div v-if="!mounted">Loading...</div>
   <child-component @hook:mounted="mountedCheck"></child-component>
</template>
<script>
export default {
export default defineComponent({
   setup() {
       const mounted = ref(false);       
       const mountedCheck = () = {
           mounted.value = true;
       }       

       return { 
           mounted, mountedCheck
       } 
   }
});
}

However, I cant seem to get the @hook:mounted to work. Is there something similar in Vue3, or am I missing something?

2 Answers

The child component needs to emit that hook

child:

<script>
export default defineComponent({
  setup() {
    onMounted(() => {
      const { emit } = getCurrentInstance();
      emit('mounted');
    })
    return {};
  }
});
</script>

parent

<template>
   <div v-if="!mounted">Loading...</div>
   <child-component @mounted="mountedCheck"></child-component>
</template>

The syntax has changed in Vue3. Now you need to use @vue:mounted instead of @hook:mounted.
See Vue 3 Migration Guide - VNode Lifecycle Events for details

Also, keep in mind that some event names like destroyed and beforeDestroy have been renamed to unmounted and beforeUnmount respectively in Vue3

Related