Alpine.js: The Dance Studio

Understanding $el, $refs, and $root through analogy.

Studio Activity Log

No activity yet. Interact with the demos below.

$el — The Current Dancer

An element referring to itself, like a dancer choosing their own move.

// The dancer element acts on itself using $el

<button @click="el_performMove($el)">
  ...
</button>

// An Alpine method receives $el as an argument

el_performMove(dancerElement) {
  // dancerElement is the button itself
  dancerElement.classList.add(...);
}

$refs — The Named Mirrors

A controller accessing specific elements by name, like a choreographer using mirrors to direct named dancers.

Choreographer's Controls

💃
Alex
🕺
Bella
👯
Chloe

// Dancers are named with x-ref

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

// The controller calls a method with the ref name

<button @click="refs_spotlight('dancerAlex')">

// The method uses $refs to find the named element

refs_spotlight(dancerRefName) {
  const dancer = this.$refs[dancerRefName];
  dancer.style.transform = 'scale(1.1)';
}

$root — The Entire Studio

An element accessing its component's root, like a light switch affecting the whole studio.

This is the Studio Floor

(This whole box is the component root)

Technician's Booth (nested)

// The component root is the bordered box with x-data

<div x-data="studioRootDemo">
  ...
    <button @click="toggleLights()">
      ...
    </button>
  ...
</div>

// The method uses $root to access that div

toggleLights() {
  // this.$root IS the div with x-data
  this.$root.classList.toggle('bg-gray-800');
}