Understanding $el, $refs, and $root
$el refers to the current DOM element the directive is on. It's like interacting directly with a piece of furniture you are touching.
<div @click="interactWithFurniture($el, 'Couch')">
...
</div>
// In Alpine.data()
interactWithFurniture(el, name) {
el.textContent = `${name} is now comfy!`;
el.classList.add('bg-green-200');
this.logAction(`Used $el on ${name}.`);
}
$refs lets you access other elements by name within your component. It's like a universal remote that can control any named electronic in the room.
<div x-ref="tv">...</div>
<button @click="controlDevice('tv')">...</button>
// In Alpine.data()
controlDevice(name) {
const device = this.$refs[name];
// ...manipulate device...
this.logAction(`Used $refs.${name}.`);
}
$root refers to the root element of the component. It's like a main light switch that affects the entire room's ambiance at once.
Room Lighting Control
<div x-data="livingRoomSetup">
<button @click="changeRoomMood()">...</button>
</div>
// In Alpine.data()
changeRoomMood() {
this.$root.classList.add('bg-indigo-100');
this.logAction('Used $root to change room.');
}
No actions taken yet. Click on the demos above!