Understanding $el, $refs, and $root
Analogy: Pressing the horn button. The action affects the button itself. $el refers to the DOM element that the event handler is on.
<!-- 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>
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.
<!-- 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>
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).
<!-- 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>
Awaiting system commands...