manipulacion-dom-con-ref-vuejs

Direct DOM Manipulation with ref in Vue.js

  • 3 min

In Vue.js, we can use ref to reference HTML elements and directly manipulate the DOM when necessary.

In general, Vue.js encourages a declarative approach to building the user interface. That is, we normally won’t have to touch DOM elements directly.

However, there are certain occasions where it will be necessary to access and manipulate DOM elements directly (third-party libraries, complex animations, certain complicated cases, etc.).

For this, Vue.js provides the ref utility, which allows us to get references to DOM elements or component instances.

Avoid directly manipulating the DOM when possible. Vue.js is designed to handle most DOM interactions declaratively.

What is ref in Vue.js

In Vue.js, we can use ref to create a reactive reference to an object or a DOM element (in addition to reactive values, as we saw when discussing reactivity).

To create a reference to a DOM element, we first import ref from Vue and then use it in the setup function.

On the other hand, in the template, we use the ref directive to bind a DOM element to the created reference.

<template>
  <div ref="miElemento">This is a DOM element</div>
</template>

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

// Create a reference
const miElemento = ref(null);

onMounted(() => {
  // Access the DOM element after it mounts
  console.log(miElemento.value); // <div>This is a DOM element</div>
});
</script>
Copied!

In this example,

  • miElemento is a reference to the <div> in the template.
  • After the component mounts (onMounted),
  • we can access the DOM element through miElemento.value.

Practical Examples

Copied!