Vue Tip: Accessing Template Ref in Child Component

Michael Hoffmann
Oct 27, 2023
| 1 min read
| 22 views
Michael Hoffmann
Oct 27, 2023
1 min read
| 22 views
Template
Script

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">
2
import { ref } from 'vue';
3
4
const innerChildRef = ref<HTMLElement | null>(null);
5
6
defineExpose({
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">
2
import { ref, onMounted } from 'vue';
3
4
import Child from './components/Child.vue';
5
6
const child = ref(null);
7
8
onMounted(() => {
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 Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:
New Vue & Nuxt tips delivered to your inbox:
Nuxt Tip: How to Fix "Nuxt Instance Unavailable" ErrorOct 12, 2023
Pinia Tip: Simple History With Undo and Redo FunctionalityNov 10, 2023
Show comments