Subscribe on changes!

Add lifecycle hook called after parent element is mounted

avatar
Sep 26th 2022

What problem does this feature solve?

considered usage

It is common that refs of parent elements are passed down to children, but when the onMounted() hook of the children is called, the ref is undefined because the parent element is not mounted yet.

the original resovement

Now in order to solve it I'm define a global state that is a boolean that have an init value to be false, then set it to be true in the onMounted() hook of the parent component. I watch it in the child component and when it chages and equals to true, i use the ref like calling addEventListener.

So i think adding a lifecycle hook called after the parent is mounted is a better choice for this.

What does the proposed API look like?

<script setup>
    let props=defineProps<{parentRef:HTMLElement}>()
    onParentMounted(()=>{props.parentRef.addEventListener('mousedown',()=>{console.log('onmousedown')})})
</script>
avatar
Sep 26th 2022

you can simply await one tick with await nextTick(). That ensures that everything being mounted in the current render cycle has been mounted properly.

onMounted(async () => {
  await nextTick()
  props.parentRef // will not be defined
})

An alternative would be to not use a lifecycle hook and instead watch the prop.

watch(
  () => props.parentRef,
  (el) => {
    if (el) {
      Do what you need to do.
   }
  }
)

All that taken into account, I don't think this use case warrants another lifecycle hook.