Alpine.js Magic Variables

Understanding $el, $refs, and $root

Using a Weather Station Analogy: Current Sensor, Named Instruments, and the Entire Facility.

$el: The Current Sensor

A sensor can act on itself. Clicking a sensor's button directly changes that specific sensor's state, without affecting others.

Sensor Array

Humidity Sensor

Wind Sensor

Code Example

<div class="sensor">
  <p>Humidity Sensor</p>
  <button @click="activateSensor($el.parentElement)">
    Activate
  </button>
</div>

$refs: Named Instruments

A central panel can query specific, named instruments from anywhere inside the facility, using their unique reference name.

Instrument Readings

Thermometer: Standby
Barometer: Standby

Central Control Panel

Code Example

<!-- 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
}

$root: The Entire Facility

An emergency button can affect the entire facility (the component's root element), triggering a system-wide alert that visually changes the whole area.

Facility Controls

Emergency System

Triggers a visual alert on the entire facility component.

Code Example

<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
}

System Log

No actions logged yet. Interact with the demos above.