Blog>
Snippets

Vue 3 Composition API with Refs

Explain the use of template refs within the Vue 3 Composition API setup function, and using the `ref` method to manipulate DOM elements.
<template>
  <div>
    <!-- Use the ref attribute to define a template ref named 'myComponent' -->
    <component ref="myComponent"></component>
    <button @click="focusOnComponent">Focus</button>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  setup() {
    // Use ref() from Vue Composition API to create a reference named 'myComponentRef'.
    const myComponentRef = ref(null);

    // This function will be called when the button is clicked.
    function focusOnComponent() {
      // The value of myComponentRef will be the actual DOM element after the component is mounted.
      // You can interact with it as you would with a regular DOM element.
      myComponentRef.value.focus();
    }

    // Wait until the component is mounted to ensure the ref is bound to the component.
    onMounted(() => {
      // After the component is mounted, the ref myComponentRef can be used to access the component.
      if (myComponentRef.value) {
        console.log('Component has been mounted');
      }
    });

    // Expose any variables or functions that should be accessible in the template.
    return {
      myComponentRef,
      focusOnComponent
    };
  }
};
</script>
In this code example, a Vue 3 component uses the Composition API to interact with a child component through a template reference (ref). A reference called 'myComponentRef' is created using the 'ref' method. This reference is linked to a DOM element in the template using the 'ref' attribute. On user interaction, the 'focusOnComponent' function is called, which focuses on the child component, demonstrating how to manipulate DOM elements with refs. Additionally, upon mounting the component, the 'onMounted' lifecycle hook is used to ensure that interactions with 'myComponentRef' occur after the component has been properly mounted.