Blog>
Snippets

Accessing DOM Elements Directly

Demonstrate how to use a template ref to access a DOM element directly in a Vue.js 3 component, such as focusing an input field on component mount.
<template>
  <input ref="myInput">
</template>

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

export default {
  setup() {
    const myInput = ref(null);

    onMounted(() => {
      if (myInput.value) {
        myInput.value.focus();
      }
    });

    return {
      myInput
    };
  }
};
</script>
This code snippet demonstrates how to access a DOM element in a Vue.js 3 component using a template ref. In the template section, an input element is defined with a ref attribute which assigns it the name 'myInput'. The setup function in the script part creates a reactive reference to this DOM element using the 'ref' function from Vue's composition API. Once the component is mounted, the onMounted lifecycle hook is used to focus the input element by accessing its 'focus' method, provided the element is successfully referenced and exists.