<template>
<HelloWorld v-if="isShow" ref="comp"></HelloWorld>
<button @click="show">Show</button>
</template>
<script>
import { defineAsyncComponent, ref, nextTick } from 'vue'
export default {
components: {
HelloWorld: defineAsyncComponent(() => import('./HelloWorld.vue))
},
setup() {
const isShow = ref(false)
const comp = ref(null)
const show = async () => {
isShow.value = true
await nextTick()
console.log(comp.value) // return null
// this works
setTimeout(() => {console.log(comp.value)}, 300)
}
return {isShow, comp, show}
}
}
</script>
I want to access HelloWorld component after mounted but console log show that comp.value is null.
It works when I use setTimeout for 300ms instead of nextTick but I don't want to use that approach. What should I do?
Here is the way I see it if you want to avoid using
setTimeout. First I apologize in advance, my solution is inComposition APII'm more comfortable with this syntax. I hope it will help you still.You need to create an
emitthat will be trigger when the component is mounted. This way, when theemitis trigger, yourcomp.valueis initialized and mounted.Parent.vue:HelloWorld.vue:Hope it helps you ! :)