Alpine.js in the Home Office

Understanding $el, $refs, and $root using an interactive home office analogy.

$el: The Current Device

$el refers to the DOM element the Alpine directive is on. It's like interacting with the very device you are touching. Click a device to see it become "active".

Active Device: None

Code Example:

<button @click="setActiveDevice($el, 'Laptop')">
  💻 Laptop
</button>

$refs: Named Supplies

$refs lets you access specific elements by name from anywhere in the component. It's like a remote control for named items in your office.

Office Supplies

💡 Lamp
🖨️ Printer
📓 Notebook
📎 Stapler

Control Panel

Code Example:

<div x-ref="deskLamp">...</div>

<button @click="toggleLamp()">...</button>

// In JS:
toggleLamp() {
  this.$refs.deskLamp.classList.toggle('active');
}

$root: The Entire Office

$root refers to the top-level element of the component. It's the master switch that affects the entire office space at once.

Code Example:

<div x-data="office">
  <button @click="powerOutage()">...</button>
</div>

// In JS:
powerOutage() {
  this.$root.classList.add('power-out');
}

Office Activity Log

  • Awaiting activity...