n Access template refs in Composition API in Vue.js 3 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

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:

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

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 {
      // ...

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.

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook