Alpine.js Magic Properties

Demonstrating $el, $refs, and $root using a Smartphone UI Analogy.

$el: The Active App

$el refers to the element the directive is on. It's like an app button that can change its own appearance or text when you tap it.

Code:

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

function changeSelf(element) {
  element.textContent = 'I changed myself!';
  element.classList.add('bg-green-500');
  // ...
}

$refs: Named Widgets

$refs lets you access other elements in the component by name. It's like a control panel that updates specific widgets on your home screen.

☀️

🎵

Code:

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

function updateWeather() {
  this.$refs.weatherWidget.classList.add('!bg-cyan-300');
  // ...
}

$root: The Entire Phone

$root refers to the top-level element of the entire component. It's like a system setting that changes the theme for the whole phone UI.

Code:

<div x-data="phoneInterface">...</div>

function toggleTheme() {
  this.$root.classList.toggle('dark-theme');
  // ...
}

Action Log:

> Waiting for interaction...