Alpine.js Guide

Directives Reference

DirectiveDescription
x-dataDeclare component data scope
x-initRun code on init
x-showToggle visibility (CSS)
x-ifConditionally render (DOM)
x-forLoop over items
x-bindBind attribute (:attr shorthand)
x-onListen to events (@event shorthand)
x-modelTwo-way data binding
x-textSet text content
x-htmlSet HTML content
x-refStore reference to element
x-cloakHide until Alpine loads
x-transitionAdd 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>