Mounted DOM Access
Part of the Fundamentals section of Coddy's Vue journey. Lesson 43 of 55.
Template refs give a component access to its rendered elements. They begin as null because setup runs before the template is mounted. Read the DOM in onMounted when the element is available.
const heading = ref(null);
const length = ref(0);
onMounted(() => { length.value = heading.value.textContent.length; });
// <h2 ref="heading">Book fair</h2>
// <p>{{ length }}</p>The example records 9, including the space in the heading. A mounted callback runs after the initial DOM is created, not after every state change. Use reactive bindings for ordinary display; use DOM access when the requirement actually needs an element property, focus or measurement.
Challenge
MediumUse a template ref named panel for p#panel containing Welcome aboard. After mounting, read that actual element's textContent.length into a ref and display 14 characters in #result. The measurement belongs in onMounted, when the element exists.
Write the measurement in MeasurePanel.vue. A supplied locked host passes the displayed label and input badge as props. Its #replace button mounts a fresh panel with label Hello. Measure each new instance from its actual DOM rather than hard-coding the initial result. The new label has five characters.
Try it yourself
<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Reactive State
Reactive RefsUpdating Refs in ScriptEvent Handler ArgumentsReactive ObjectsRecap: Reactive State5Conditions and Lists
Conditional BranchesShow without UnmountingRendering ListsStable List IdentityRecap: Conditions8Component Communication
Emitting EventsEvent PayloadsLifting Shared StateDefault and Named SlotsRecap: Shared Panel11Project: Community Board
Board StructureAdding Community Tasks6Working with Lists
Adding List ItemsRemoving by IdComputed Search ResultsCounts from ListsRecap: List Manager9Watchers and Lifecycle
Watching a RefWatching Object FieldsMounted DOM AccessCleaning Up on UnmountRecap: Activity Log