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>