Suggest an editImprove this articleRefine the answer for “How do you access the DOM through ref?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**A template ref** is how you access a real DOM element in Vue: you create `ref(null)`, bind it in the template through the `ref` attribute, and access the element via `.value` inside `onMounted`. **Key point:** before the component mounts, `inputEl.value` is `null`, so DOM access is only possible after mounted.Shown above the full answer for quick recall.Answer (EN)ImageTo access the DOM through `ref` in Vue, you use a **template ref** - a `ref` that is bound to a real DOM element. Access to the DOM becomes available **only after the component is mounted**. --- ## 1. Using ref in the Composition API ### Step 1: create a ref variable ```js const inputEl = ref(null) ``` ### Step 2: bind it in the template ```html <input ref="inputEl" /> ``` ### Step 3: access it in onMounted ```js onMounted(() => { inputEl.value.focus() // inputEl.value is the real DOM element }) ``` --- ## A full example ```vue <script setup> import { ref, onMounted } from 'vue' const inputEl = ref(null) onMounted(() => { console.log(inputEl.value) // <input ...> inputEl.value.focus() }) </script> <template> <input ref="inputEl" /> </template> ``` --- ## What can you do with the DOM element? ```js inputEl.value.focus() inputEl.value.blur() inputEl.value.style.color = 'red' inputEl.value.classList.add('active') inputEl.value.getBoundingClientRect() ``` Any methods of regular DOM elements are available. --- ## Important rules #### 1. ref is available only after onMounted Before mounting: ```js console.log(inputEl.value) // null ``` #### 2. ref returns the DOM element itself Not a reactive object, it is a direct reference to the element. #### 3. If the element is hidden through v-if ref will be `null` until the element appears. #### 4. With v-for, ref → an array of refs For example: ```html <div v-for="item in items" :ref="elRefs">...</div> ``` --- ## Example with a "Scroll to element" button ```vue <script setup> import { ref, onMounted } from 'vue' const box = ref(null) function scrollToBox() { box.value.scrollIntoView({ behavior: 'smooth' }) } </script> <template> <button @click="scrollToBox">Scroll</button> <div ref="box" style="margin-top:1000px">Target</div> </template> ```For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.