Sometimes you need to access a template ref of a nested component. For example, you want to focus an input field in a child component from the parent component.
Let's take a look at how you can do this in Vue 3:
<script setup lang="ts">
import { ref } from 'vue';
const innerChildRef = ref<HTMLElement | null>(null);
defineExpose({
innerChildRef,
});
</script>
<template>
<div ref="innerChildRef">
<!-- child content -->
</div>
</template>
</style>
In the child component, we define a template ref called innerChildRef
and expose it to the parent component using defineExpose()
.
Now you can access this template ref in the parent component:
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import Child from './components/Child.vue';
const child = ref(null);
onMounted(() => {
if (child.value) {
console.log('Inner Child ref', child.value.innerChildRef);
}
});
</script>
<template>
<Child ref="child" />
</template>
StackBlitz Demo
Try it yourself in the following StackBlitz project:
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :
Pinia Tip: Simple History With Undo and Redo Functionality
Nuxt Tip: How to Fix "Nuxt Instance Unavailable" Error