·
1 min read

Vue Tip: Accessing Template Ref in Child Component

MH

Michael Hoffmann

@mokkapps

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
<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:

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

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