Understanding $el, $refs, and $root
$el refers to the current DOM element. A swimmer (the button) can only interact with their own lane (the div).
<button @click="toggleLane($el)">Jump In</button>
<script>
function toggleLane(buttonEl) {
const lane = buttonEl.closest('.lane');
lane.classList.toggle('bg-blue-300');
// ... and update button text
}
</script>
$refs accesses named elements from anywhere in the component. A lifeguard (the control panel) can manage specific facilities (the named areas).
Status: Open
Status: Open
<div x-ref="waterSlide">...</div>
<button @click="toggleFacility('waterSlide')">...</button>
<script>
function toggleFacility(facilityName) {
const facility = this.$refs[facilityName];
facility.classList.toggle('bg-yellow-200');
// ...
}
</script>
$root refers to the component's root DOM element. This is like a complex-wide emergency system (the button) that affects everything (the entire component area).
Clicking the button will add a class to the main component's root element, triggering a CSS overlay.
<div x-data="poolComplex">
<!-- This is $root -->
<button @click="toggleComplexShutdown">...</button>
</div>
<script>
function toggleComplexShutdown() {
this.$root.classList.toggle('complex-closed');
}
</script>