Template Refs

We can use template refs to directly access elements in our template:

<template>
<div>
<input
type="text"
placeholder="Start typing..."
ref="input"
/>
</div>
</template>

When using the composition API, we provide the ref, and Vue will set the value to the element of the same name:

<script setup>
import { ref, onMounted } from "vue";
onMounted(() => {
// Once mounted it's assigned the DOM element
input.value.focus();
});
// Initially set to null
const input = ref(null);
</script>

If we're using the options API it's a bit different. Instead of creating a ref ourselves, we have to access the template ref through a special $refs object:

<script>
export default {
mounted() {
// Access our input using template refs, then focus
this.$refs.input.focus()
}
}
</script>