Demonstrating $el, $refs, and $root with a forest ecosystem analogy.
$el refers to the current DOM element. Actions only affect the tree you interact with.
<button @click="inspectTree($el)">...</button>
// In component:
inspectTree(treeElement) {
// Reset others first
this.trees.forEach(t => t.inspected = false);
// Mark this one as inspected visually
treeElement.parentElement.classList.add(...)
// Update a log
Alpine.store('logStore').add('$el: Inspected a tree.');
}
$refs lets you access specific, named elements from anywhere in the component. Useful for remote control.
<div x-ref="bearCave">...</div>
<button @click="checkWildlife('bearCave')">...</button>
// In component:
checkWildlife(area) {
this.$refs[area].style.transform = 'scale(1.05)';
this.wildlife[area].status = 'All clear!';
}
$root refers to the component's root element. Use it to make changes that affect the entire component boundary.
Change the forest's season, affecting the entire container's appearance.
<div x-data="forestEcosystem">
<button @click="changeSeason('winter')">...</button>
</div>
// In component:
changeSeason(season) {
// Remove all season classes
this.$root.classList.remove(...)
// Add the new season class
this.$root.classList.add(`season-${season}`);
}