Back
VueMediumNew

How do you access a DOM element or child component instance directly with template refs?

ref() with a matching template ref attribute

Ideal Answer

Declare a ref() with the same name as the ref attribute in the template; Vue automatically binds the DOM element (or child component's public instance) to it after mount.

JavaScript
<script setup>
import { ref, onMounted } from 'vue'

const inputEl = ref(null)

onMounted(() => {
  inputEl.value.focus()
})
</script>

<template>
  <input ref="inputEl" />
</template>

For child components using <script setup>, only what's explicitly exposed via defineExpose is accessible through the template ref, since <script setup> components are closed by default.