Accessing Template Refs Using Composition API in Vue 3

Dec 04, 2025 · Programming · 9 views · 7.8

Keywords: Vue3 | Composition API | Template Refs | JavaScript | Vue.js

Abstract: This article explains how to correctly access template references ($refs) in Vue 3 when using the Composition API. It compares the traditional Options API approach with the new method, provides step-by-step code examples, and addresses common pitfalls such as why getCurrentInstance().$refs might be undefined.

Introduction

Vue 3 introduces the Composition API, a new paradigm for organizing component logic in a more modular way. One essential aspect of component interaction is accessing template references, commonly known as $refs, to directly manipulate DOM elements or child component instances.

What are Template Refs?

In Vue.js, template refs are special attributes that allow developers to obtain a direct reference to a specific DOM element or child component after it has been mounted. This is useful for tasks such as focusing an input or calling methods on a child component.

Traditional Approach with Options API

In the Options API, template refs are accessed via the this.$refs object within lifecycle hooks like mounted. For example:

mounted() {
    console.log(this.$refs.table.temp());
}

This method is straightforward but limited to the Options API structure.

New Approach with Composition API

With the Composition API, the process changes. You need to use the ref function from Vue to create a reactive reference and then return it from the setup function. Here's the correct way:

import { ref, onMounted } from 'vue';

setup() {
    const table = ref(null);

    onMounted(() => {
        console.log(table.value);
    });

    return { table };
}

In the template, bind the ref attribute to the returned value:

<template>
    <div ref="table"/>
</template>

This ensures that the reference is properly initialized and accessible in the onMounted hook.

Why getCurrentInstance().$refs Might Not Work

A common mistake when transitioning to the Composition API is attempting to access refs using getCurrentInstance().$refs. This often results in undefined because the refs are not populated until after the component is mounted. The Composition API requires a more explicit approach with the ref function.

Conclusion

The Composition API offers greater flexibility for managing component logic. To access template refs effectively, adopt the method of creating a ref with the ref function and accessing it within lifecycle hooks. This approach aligns with Vue 3's reactive system and ensures reliable component interaction.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.