·
1 min read

Vue Tip: Accessing Template Ref in Child Component

Vue Tip: Accessing Template Ref in Child Component Image

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:

Child.vue
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:

Parent.vue
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:

I will never share any of your personal data. You can unsubscribe at any time.