Demonstrating $el, $refs, and $root
Analogy: You're tapping a smart bulb directly. $el refers to the element you are interacting with.
<button @click="toggleLight()">...</button>
// In Alpine.data component:
toggleLight() {
this.lightIsOn = !this.lightIsOn;
// Use $el for a one-off effect
this.$el.classList.add('animate-pulse-once');
setTimeout(() => this.$el.classList.remove('animate-pulse-once'), 500);
Alpine.store('systemLog').log('$el: Toggled smart bulb directly.');
}
Analogy: Using a central remote to control specific appliances by name, like the "Living Room TV".
📺 Living Room TV
Status: OFF
🌡️ Kitchen Thermostat
Set to:
<div x-ref="livingRoomTV">...</div>
<button @click="operateTV()">...</button>
// In Alpine.data component:
operateTV() {
// ... update state ...
this.$refs.livingRoomTV.classList.add('bg-blue-100');
this.$refs.tvStatus.textContent = 'Status: ON';
Alpine.store('systemLog').log('$refs: Used remote for TV.');
}
Analogy: Activating a scene like "Goodnight" which affects the entire house component from a single button.
Current House Mode:
<div x-data="smartHomeSystem">
<!-- Deeply nested button -->
<button @click="setHouseMode('night')">...</button>
</div>
// In Alpine.data component:
setHouseMode(mode) {
this.houseMode = mode;
// $root refers to the top-level div[x-data]
if (mode === 'night') {
this.$root.classList.add('dark');
Alpine.store('systemLog').log('$root: Whole house set to night.');
} else {
this.$root.classList.remove('dark');
Alpine.store('systemLog').log('$root: Whole house set to day.');
}
}
$el
Refers to the DOM element the Alpine directive is on. Useful for one-off, direct manipulations from an event handler.
$refs
Accesses other DOM elements within the same component that have an x-ref attribute. Perfect for a "controller" to manipulate specific "parts".
$root
Refers to the root DOM element of the current Alpine component. Ideal for broad actions that affect the whole component boundary, regardless of how deeply nested the trigger is.