Refs work a bit differently in Composition API as compared to the Options API. In the Options API, we could declare any element with a ref like this:
<h1 ref="titleRef">
My title
</h1>
Code language: HTML, XML (xml)
And then access it using the this.$refs.titleRef accessor. However in the Composition API, we can access it using the ref method. Let’s have a look at how we can change the h1 text when our app is mounted using the ref method.
We have the following template with a ref named titleRef referencing to the h1 title.
<template>
<div>
<h1 ref="titleRef">
My title
</h1>
</div>
</template>
Code language: HTML, XML (xml)
We can now change the h1 title text as follows:
<script setup>
import { ref, onMounted } from "vue";
//this.$refs.titleRef
const titleRef = ref(null)
onMounted(() => {
titleRef.value.innerHTML = 'Updated title!'
})
</script>
Code language: HTML, XML (xml)
As you can see from the above code, we can access the ref element using the ref name directly. We can access its value using the .value accessor.