Understanding $el, $refs, and $root
Using a Weather Station Analogy: Current Sensor, Named Instruments, and the Entire Facility.
A sensor can act on itself. Clicking a sensor's button directly changes that specific sensor's state, without affecting others.
Humidity Sensor
Wind Sensor
<div class="sensor">
<p>Humidity Sensor</p>
<button @click="activateSensor($el.parentElement)">
Activate
</button>
</div>
A central panel can query specific, named instruments from anywhere inside the facility, using their unique reference name.
<!-- Instrument -->
<div x-ref="thermometer">...</div>
<!-- Control Button -->
<button @click="readInstrument('thermometer')">
Read Temp
</button>
// JS Logic
readInstrument(name) {
let el = this.$refs[name];
// ... manipulate el
}
An emergency button can affect the entire facility (the component's root element), triggering a system-wide alert that visually changes the whole area.
Triggers a visual alert on the entire facility component.
<div x-data="weatherStation" x-ref="facility">
...
<button @click="triggerFacilityAlert()">
Alert
</button>
</div>
// JS Logic
triggerFacilityAlert() {
this.$root.classList.add('alert-active');
// $root is the div with x-data
}