JAVASCRIPT

Access DOM Elements Directly with Vue 3 ref

Discover how to use Vue 3's `ref` attribute and `ref()` function to gain direct programmatic access to specific DOM elements or child component instances within your templates.

<template>
  <div>
    <input type="text" ref="myInput" placeholder="Type something...">
    <button @click="focusInput">Focus Input</button>
  </div>
</template>

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

// Create a ref object that will hold the DOM element reference
const myInput = ref(null);

const focusInput = () => {
  // Access the DOM element via .value and call its methods
  if (myInput.value) {
    myInput.value.focus();
    myInput.value.style.borderColor = 'blue';
  }
};

onMounted(() => {
  // You can also access it on mount, for example, to autofocus
  // myInput.value.focus();
});
</script>
How it works: In Vue 3, the `ref` attribute is used in the template to register a reference to a DOM element or a child component instance. By creating a corresponding reactive `ref` variable (e.g., `const myInput = ref(null);`) in your script, Vue automatically populates this variable's `.value` property with the actual DOM element or component instance once it's mounted. This provides direct programmatic access, enabling actions like focusing an input, manipulating styles, or calling methods on child components.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs