N
Nuxt2mo ago
eym

using ref alongside conditional rendering (useTemplateRef + v-if)

Hi, in my situation I have some component that will be rendered conditionally. I also need to assign the useTemplateRef() for each one of them that I will be calling functions exported using defineExpose(). The problem is that useTemplateRef or ref can not be assigned to the component if the component is not rendered at first. One solution is to use v-show but that doesn't really satisfy me and I don't want the other components shown in devtools.
<script setup lang="ts">
import CheckMobile from '~/components/pages/auth/CheckMobile.vue';
import VerifyMobile from '~/components/pages/auth/VerifyMobile.vue';

const status = ref<Status>(Status.CHECK_MOBILE); // enum

const VerifyMobileRef = useTemplateRef<InstanceType<typeof VerifyMobile>>('verifyMobile');

const onMobileChecked = () => {
status.value = Status.VERIFY_MOBILE;
VerifyMobileRef.value?.startCountdown(); // Doesn't work
};
</script>

<template>
<CheckMobile
v-if="status === Status.CHECK_MOBILE"
@mobile-checked="onMobileChecked"
/>
<VerifyMobile
v-if="status === Status.VERIFY_MOBILE"
ref="verifyMobile"
/>
<template>
<script setup lang="ts">
import CheckMobile from '~/components/pages/auth/CheckMobile.vue';
import VerifyMobile from '~/components/pages/auth/VerifyMobile.vue';

const status = ref<Status>(Status.CHECK_MOBILE); // enum

const VerifyMobileRef = useTemplateRef<InstanceType<typeof VerifyMobile>>('verifyMobile');

const onMobileChecked = () => {
status.value = Status.VERIFY_MOBILE;
VerifyMobileRef.value?.startCountdown(); // Doesn't work
};
</script>

<template>
<CheckMobile
v-if="status === Status.CHECK_MOBILE"
@mobile-checked="onMobileChecked"
/>
<VerifyMobile
v-if="status === Status.VERIFY_MOBILE"
ref="verifyMobile"
/>
<template>
2 Replies
dwol
dwol2mo ago
Are you sure the verify mobile component is mounted when you try running the start countdown function? You might need to ‘await nextTick()’ or use a setTimeout
eym
eymOP2mo ago
I fixed it. It was because the useTemplateRef is initialized before the component actually gets rendered so it is undefined at first. I used a watcher on the useTemplateRef and the interesting part is that it is reactive.
watch(VerifyMobileRef, () => {
VerifyMobileRef.value?.startCountdown();
});
watch(VerifyMobileRef, () => {
VerifyMobileRef.value?.startCountdown();
});
Want results from more Discord servers?
Add your server