Alpine.js
Handling browser state.
Properties: Alpine.js behavior
Does not fetch data from server. Only HTMX does.
State’s father is
x-data. Keep the scope within one html file.Event driven.
$dispatch('event-name')to dispatch.@htmx:after-requestto listen.
Workflow: Creating global components
Create ./static/js/componentName.js:
document.addEventListener('alpine:init', () => { Alpine.data('componentName', () => ({ count: 0, increment() { this.count++ } })); });
Customize as needed:
Load into base:
<script src="{% static 'js/componentName.js' %}"></script>Use
x-data="componentName"to invoke:<div x-data="componentName"> <span x-text="count"></span> <button @click="increment">Click Me</button> </div>
Properties: Insides of Alpine.data('componentName', () => ({ ... }))
Variables:
count: 0Methods:
increment() { this.count++ }The constructor:
init() {console.log('hello!')}
Properties: Magics
$refs: Accesses DOM elements marked withx-ref.$el: References the current element where the expression is executed.$dispatch: Fires custom browser events that can bubble up.$nextTick: Executes code only after Alpine has finished updating the DOM.$watch: Monitors changes to a specific data property.
Workflow: Using $refs to access DOM elements directly:
Select the target element inside an
x-datascope.Assign a reference name using the
x-ref="name"attribute.Call the element using $refs.name within your Alpine expressions.
Perform standard DOM operations like .focus(), .scrollIntoView(), or .innerHTML = ‘’.