Alpine.js Dashboard

Understanding $el, $refs, and $root

$el: The Current Control

Analogy: Pressing the horn button. The action affects the button itself. $el refers to the DOM element that the event handler is on.

Code Example

<!-- The button references itself with $el -->
<button @click="honk($el)">
    Horn
</button>

<script>
    Alpine.data('elDemo', () => ({
        buttonText: 'Horn',
        honk(element) {
            // `element` is the button DOM node
            element.classList.add('animate-ping');
            this.buttonText = 'HONK!';
            // ...
        }
    }))
</script>

$refs: Named Systems

Analogy: Using steering wheel controls to operate specific, named systems like the radio or A/C. $refs lets you access other elements in the component by name.

RADIO

A/C

Code Example

<!-- Displays are named with x-ref -->
<p x-ref="radioDisplay"></p>
<p x-ref="acDisplay"></p>

<!-- Button triggers a method -->
<button @click="tuneRadio">Tune Radio</button>

<script>
    Alpine.data('refsDemo', () => ({
        tuneRadio() {
            // Access named element via this.$refs
            this.$refs.radioDisplay.classList.add('bg-green-900');
            // ...
        }
    }))
</script>

$root: The Entire Vehicle

Analogy: An emergency alert that affects the entire vehicle, making the whole dashboard flash. $root refers to the component's top-level DOM element (the one with x-data).

Code Example

<!-- The component's root element -->
<section x-data="rootDemo">
    <button @click="triggerAlert">
        Trigger Alert
    </button>
</section>

<script>
    Alpine.data('rootDemo', () => ({
        triggerAlert() {
            // Access the root <section> with this.$root
            this.$root.classList.add('animate-shake', 'border-red-500');
            // ...
        }
    }))
</script>

Dashboard System Log