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:
1<script setup lang="ts">
2import { ref } from 'vue';
3
4const innerChildRef = ref<HTMLElement | null>(null);
5
6defineExpose({
7 innerChildRef,
8});
9</script>
10
11<template>
12 <div ref="innerChildRef">
13 <!-- child content -->
14 </div>
15</template>
16</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:
1<script setup lang="ts">
2import { ref, onMounted } from 'vue';
3
4import Child from './components/Child.vue';
5
6const child = ref(null);
7
8onMounted(() => {
9 if (child.value) {
10 console.log('Inner Child ref', child.value.innerChildRef);
11 }
12});
13</script>
14
15<template>
16 <Child ref="child" />
17</template>
StackBlitz Demo
Try it yourself in the following StackBlitz project:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: How to Fix "Nuxt Instance Unavailable" Error
If you are using Nuxt 3, you probably already encountered the 'Nuxt Instance Unavailable' error. What is it, and how to fix it?
Pinia Tip: Simple History With Undo and Redo Functionality
Build a simple history with undo and redo functionality using the useRefHistory composable from VueUse.