Alpine.js Guide
Directives Reference
| Directive | Description |
|---|---|
| x-data | Declare component data scope |
| x-init | Run code on init |
| x-show | Toggle visibility (CSS) |
| x-if | Conditionally render (DOM) |
| x-for | Loop over items |
| x-bind | Bind attribute (:attr shorthand) |
| x-on | Listen to events (@event shorthand) |
| x-model | Two-way data binding |
| x-text | Set text content |
| x-html | Set HTML content |
| x-ref | Store reference to element |
| x-cloak | Hide until Alpine loads |
| x-transition | Add CSS transitions |
Counter Example
<div x-data="{ count: 0 }">
<button @click="count--">-</button>
<span x-text="count"></span>
<button @click="count++">+</button>
</div>
Fetch Data
<div x-data="{
users: [],
async init() {
const res = await fetch('/api/users');
this.users = await res.json();
}
}">
<template x-for="user in users" :key="user.id">
<div>
<span x-text="user.name"></span>
<a :href="'/users/' + user.id">View</a>
</div>
</template>
</div>
Reusable Component with Alpine.data
Alpine.data('dropdown', () => ({
open: false,
toggle() { this.open = !this.open; },
close() { this.open = false; }
}));
// HTML
<div x-data="dropdown">
<button @click="toggle">Menu</button>
<div x-show="open" @click.outside="close">
<!-- dropdown content -->
</div>
</div>