Demonstrating $el, $refs, and $root with an aircraft cockpit analogy.
Analogy: A specific button or display that knows about itself. Pressing it causes it to light up or change its own text.
<!-- The button modifies itself using $el -->
<button @click="toggle($el)">
Engine: OFF
</button>
<script>
// In an Alpine.data component...
toggle(buttonElement) {
// 'buttonElement' is the DOM node ($el)
buttonElement.textContent = 'Engine: ON';
buttonElement.classList.add('bg-green-600');
}
</script>
Analogy: A master switch that can activate other specific, named controls (like landing gear, flaps, etc.) from one place.
<!-- Elements are given names with x-ref -->
<div x-ref="fuelIndicator">...</div>
<div x-ref="navIndicator">...</div>
<button @click="runCheck">Run Check</button>
<script>
// Logic accesses named elements via this.$refs
runCheck() {
this.$refs.fuelIndicator.textContent = '...';
this.$refs.navIndicator.classList.add('bg-yellow-500');
}
</script>
Analogy: The entire cockpit panel. An emergency button can make the entire panel flash with red alert lights.
Activates an alert on this entire component panel.
<!-- The component's root element -->
<div x-data="rootDemo">
<button @click="toggleAlert">Toggle...</button>
</div>
<script>
// Logic modifies the component's root element
toggleAlert() {
// this.$root refers to the <div x-data...>
this.$root.classList.toggle('animate-pulse-border');
}
</script>