Access template refs in Composition API in Vue.js 3

You've seen in the last tip "Use old instance properties in Composition API in Vue.js 3" how to access instance properties in the new syntax.

However, our beloved this.$refs wasn't included in the setup context object as you realized if you read the tip.

So, how can you work with template refs in Composition API?

It might be more simple than you think! The thing is, Vue.js unifies the concept of refs, meaning that you just need to use the ref() function you already know for declaring reactive state variables in order to declare a template ref as well.

Only keep in mind that the ref name must be the same as the variable's one. Let me illustrate it. For the template:

<template>
  <div>
    <h2 ref="titleRef">{{ formattedMoney }}</h2>
    <input v-model="delta" type="number" />
    <button @click="add">Add</button>
  </div>
</template>

I've set titleRef on the <h2> tag. That's all in the template level. Now in the setup function, you need to declare a ref with the same titleRef name, initialized to null for instance:

export default {
  setup(props) {
    // Refs
    const titleRef = ref(null);

    // Hooks
    onMounted(() => {
      console.log("titleRef", titleRef.value);
    });

    return {
      titleRef
      // ...
    };
  }
};

You access the ref value just like any other reactive ref, by accessing the .value property. If you do so as shown in the example you should see in the console the result titleRef

10.00

Don't believe me? Check it out with your own eyes this CodeSandbox!

That's it for today's tip!

Don't miss out anything about Vue, your favourite framework.

Subscribe to receive all the articles we publish in a concise format, perfect for busy devs.

Related Articles

How to use script setup in Nuxt 2

If you love Vue script setup and want to use it in your current Nuxt 2 project, the Nuxt team has made it possible to start using it today!

Paul Melero

Paul Melero

Feb 14, 2022

Use Composition API to easily handle API requests in Vue.js

Not sure how to organize your API client in Vue.js? Learn this simple technique on how to do it using the new Composition API and make it easy.

Carlos Rodrigues

Carlos Rodrigues

Jul 6, 2020

Create a i18n Plugin with Composition API in Vue.js 3

A example on how to use the inject and provide functions to create a i18n plugin using Composition API in Vue.js 3.

Alex Jover Morales

Alex Jover Morales

Feb 17, 2020

Sponsors

VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

Silver
Learning Partner