Alpine.js gives you reactive, declarative UI in HTML attributes — like Vue but without the build step. Perfect for adding interactivity to server-rendered pages.
Getting Started
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
Core Directives
Toggle & Show
<div x-data="{ open: false }">
<button @click="open = !open">Toggle Menu</button>
<nav x-show="open" x-transition>
<a href="/home">Home</a>
<a href="/about">About</a>
</nav>
</div>
Lists & Loops
<div x-data="{ todos: [], newTodo: '' }">
<form @submit.prevent="todos.push({ text: newTodo, done: false }); newTodo = ''">
<input x-model="newTodo" placeholder="Add todo">
<button>Add</button>
</form>
<template x-for="(todo, i) in todos" :key="i">
<div>
<input type="checkbox" x-model="todo.done">
<span :class="todo.done && 'line-through'" x-text="todo.text"></span>
<button @click="todos.splice(i, 1)">x</button>
</div>
</template>
<p x-text="'Done: ' + todos.filter(t => t.done).length + '/' + todos.length"></p>
</div>
Fetch Data
<div x-data="{ users: [], loading: true }"
x-init="fetch('/api/users').then(r => r.json()).then(d => { users = d; loading = false })">
<div x-show="loading">Loading...</div>
<template x-for="user in users" :key="user.id">
<div x-text="user.name"></div>
</template>
</div>
Stores (Global State)
<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>
<button @click="$store.cart.add({ name: 'Widget', price: 9.99 })">Add to Cart</button>
<span x-text="'Cart: $' + $store.cart.total"></span>
Why This Matters
- No build step: CDN script tag, done
- 15 directives: Learn in an afternoon
- 17KB: vs 100KB+ for Vue/React
- Server-friendly: Enhances any HTML, any backend
Need custom frontend tools or interactive components? I build developer tools. Check out my web scraping actors on Apify or reach out at spinov001@gmail.com for custom solutions.
Top comments (0)