How to access $refs in VueJS 3 with the composition API and script setup

In Vuejs 2 you could access specific elements of the DOM using $refs.

In Vue 3 with the new composition API, $refs is no longer available. Instead, you can simply use the new ref() function as a replacement for HTML element references.

<template>
  <div ref="myReference">...</div>
</template>

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

// see how this variable's name match the ref in the template
const myReference = ref(null);

onMounted(() => {
  // myReference.value is no longer null after onMounted
  console.log(myReference.value.textContent);
});
</script>
1 email / week to learn how to (ab)use technology for fun & profit: Programming, Hacking & Entrepreneurship.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Tags: programming, webdev, vuejs

Want to learn Rust, Cryptography and Security? Get my book Black Hat Rust!