We can use template refs to directly access elements in our template:
<template><div><inputtype="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 elementinput.value.focus();});// Initially set to nullconst 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 focusthis.$refs.input.focus()}}</script>