Loading...
Loading...
AlpineJS best practices and patterns. Use when writing HTML with Alpine.js directives to avoid common mistakes like long inline JavaScript strings.
npx skill4agent add brettatoms/agent-skills alpinejsx-datax-init| Directive | Purpose | Example |
|---|---|---|
| Declare reactive component state | |
| Run code on component init | |
| Toggle visibility (CSS display) | |
| Conditional rendering (must wrap | |
| Loop (must wrap | |
| Bind attribute to expression | |
| Listen to events | |
| Two-way bind form inputs | |
| Set text content | |
| Set inner HTML | |
| Reference element via | |
| Hide until Alpine initializes | |
| Apply enter/leave transitions | |
| Run reactive side effects | |
| Skip Alpine initialization | |
| Move element to another location | |
| Expose property for external binding | |
| Property | Description |
|---|---|
| Current DOM element |
| Access elements with |
| Access global Alpine stores |
| Watch a property for changes |
| Dispatch custom events |
| Run after DOM updates |
| Root element of component |
| Access component data object |
| Generate unique IDs |
<!-- DON'T DO THIS -->
<div x-data="{ items: [], loading: true, error: null, async fetchItems() { this.loading = true; try { const res = await fetch('/api/items'); this.items = await res.json(); } catch (e) { this.error = e.message; } finally { this.loading = false; } } }" x-init="fetchItems()"><script>
function itemList() {
return {
items: [],
loading: true,
error: null,
async fetchItems() {
this.loading = true;
try {
const res = await fetch('/api/items');
this.items = await res.json();
} catch (e) {
this.error = e.message;
} finally {
this.loading = false;
}
}
};
}
</script>
<div x-data="itemList()" x-init="fetchItems()">
<!-- template -->
</div><!-- Simple state is fine inline -->
<div x-data="{ open: false, count: 0 }">
<button @click="open = !open">Toggle</button>
<div x-show="open" x-transition>Content</div>
</div><script>
document.addEventListener('alpine:init', () => {
Alpine.store('cart', {
items: [],
add(item) { this.items.push(item); },
get total() { return this.items.reduce((sum, i) => sum + i.price, 0); }
});
});
</script>
<div x-data>
<span x-text="$store.cart.total"></span>
</div><script>
document.addEventListener('alpine:init', () => {
Alpine.data('dropdown', () => ({
open: false,
toggle() { this.open = !this.open; },
close() { this.open = false; }
}));
});
</script>
<div x-data="dropdown" @click.outside="close()">
<button @click="toggle()">Menu</button>
<ul x-show="open" x-transition>
<li>Item 1</li>
</ul>
</div><script>
function contactForm() {
return {
email: '',
message: '',
errors: {},
validate() {
this.errors = {};
if (!this.email.includes('@')) this.errors.email = 'Invalid email';
if (this.message.length < 10) this.errors.message = 'Too short';
return Object.keys(this.errors).length === 0;
},
submit() {
if (this.validate()) {
// submit logic
}
}
};
}
</script>
<form x-data="contactForm()" @submit.prevent="submit()">
<input x-model="email" type="email">
<span x-show="errors.email" x-text="errors.email" class="error"></span>
<textarea x-model="message"></textarea>
<span x-show="errors.message" x-text="errors.message" class="error"></span>
<button type="submit">Send</button>
</form>@click.prevent <!-- preventDefault() -->
@click.stop <!-- stopPropagation() -->
@click.outside <!-- Click outside element -->
@click.window <!-- Listen on window -->
@click.document <!-- Listen on document -->
@click.once <!-- Fire once -->
@click.debounce <!-- Debounce (default 250ms) -->
@click.throttle <!-- Throttle -->
@keydown.enter <!-- Specific key -->
@keydown.escape <!-- Escape key -->x-transition <!-- Default fade -->
x-transition.duration.300ms <!-- Custom duration -->
x-transition.opacity <!-- Opacity only -->
x-transition.scale.90 <!-- Scale from 90% -->
x-transition:enter.duration.500ms <!-- Enter duration -->
x-transition:leave.duration.200ms <!-- Leave duration -->x-data="{ open: false }"function componentName() { return {...} }Alpine.data('name', () => ({...}))Alpine.store('name', {...})