Demonstrating $el, $refs, and $root through an interactive analogy.
Analogy: An action that affects only the specific piece of equipment being interacted with. $el refers to the current DOM element the directive is on.
<button @click="toggleEquipment($el)" data-name="Treadmill">
Use Treadmill
</button>
<script>
//...
toggleEquipment(el) {
const name = el.dataset.name;
const inUse = el.dataset.inUse === 'true';
// ... logic to update el.textContent, el.classList, etc.
}
//...
</script>
Analogy: A central control panel that activates systems in specific, named zones of the facility. $refs provides access to elements marked with x-ref within the component.
<button @click="toggleZone('cardioZone')">...</button>
<div x-ref="cardioZone">
... <span x-ref="cardioZoneStatus">Inactive</span>
</div>
<script>
//...
toggleZone(zoneName) {
const zoneEl = this.$refs[zoneName];
const statusEl = this.$refs[zoneName + 'Status'];
// ... logic to update zoneEl.classList and statusEl.textContent
}
//...
</script>
Analogy: An emergency button that triggers an alert across the entire facility. $root refers to the root element of the current Alpine component.
FACILITY-WIDE ALERT ACTIVE!
<div x-data="trainingFacility"> <!-- This is $root -->
<button @click="toggleEmergency()">...</button>
</div>
<script>
//...
inEmergency: false,
toggleEmergency() {
this.inEmergency = !this.inEmergency;
this.$root.classList.toggle('animate-pulse-border');
}
//...
</script>
All actions are logged here in real-time. Use the reset button to start over.