Search code examples
javascripttypescriptvue.jsvuejs3

How to get $refs using Composition API in Vue3?


I am trying to get $refs in Vue 3 using Composition API. This is my template that has two child components and I need to get reference to one child component instance:

<template>
    <comp-foo />
    <comp-bar ref="table"/>
</template>

In my code I use Template Refs: ref is a special attribute, that allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted.

If I use Options API then I don't have any problems:

  mounted() {
    console.log("Mounted - ok");
    console.log(this.$refs.table.temp());
  }

However, using Composition API I get error:

setup() {
    const that: any = getCurrentInstance();
    onMounted(() => {
      console.log("Mounted - ok");
      console.log(that.$refs.table.temp());//ERROR that.$refs is undefined
    });
    return {};
  }

Could anyone say how to do it using Composition API?


Solution

  • You need to create the ref const inside the setup then return it so it can be used in the html.

    <template>
        <div ref="table"/>
    </template>
    
    import { ref, onMounted } from 'vue';
    
    setup() {
        const table = ref(null);
    
        onMounted(() => {
          console.log(table.value);
        });
    
        return { table };
    }