Exploring $el, $refs, and $root
An element modifying itself.
This button represents an interactive exhibit. Clicking it will make it "light up" by changing its own styles and text using $el.
// In Alpine.data('exhibit')
interact() {
const button = this.$el.querySelector('button');
// ...change button's class and text
this.$dispatch('log', 'Exhibit ($el) was activated.');
}
One element controlling other named elements.
From the curator's desk, we can spotlight specific named displays (x-ref) around the room using $refs.
// In Alpine.data('curatorDesk')
spotlight(refName) {
this.$refs[refName].classList.add('ring-4');
// ...
this.$dispatch('log', `Used $refs for '${refName}'.`);
}
A nested element affecting its component's root.
An event coordinator inside the museum needs to announce closing time. This action, triggered from a nested component, affects the entire museum (the component's root element with x-data="museum") using $root.
// In Alpine.data('eventCoordinator')
announceClosing() {
this.$root.classList.add('bg-slate-800');
// ...
this.$dispatch('log', 'Used $root for closing.');
}