You will get the Alpine JS complete cheat sheet with a PDF file in this tutorial.
Table of Contents
Why Alpine JS?
Alpine.js provides the reactive and declarative features of large frameworks such as Vue or React in a very simple approach.
Alpine.js is small (7kB gzip) and designed for writing markup-driven client-side JavaScript.
The syntax is similar to Vue and the Angular directive.
The rise of utility-based solutions such as Tailwind CSS has recently done an amazing job with CSS, while Alpine.js promises something similar for JavaScript.
Let’s see an example, display the current year in the footer. It doesn’t require adding an additional JavaScript file. You can do almost everything while staying on the same page.
This Alpine JS cheat sheet will help you to look at the syntax quickly while coding.
Read More: Git commands cheat sheet and Laravel Blade Template cheat sheet
<div>
Copyright ©
<span x-text="new Date().getFullYear()"></span>
</div>
Installation of Alpine.js
Install using CDN
<head>
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
</head>
OR use it as an npm module
npm install alpinejs
Import in your JavaScript File
import Alpine from 'alpinejs'
window.Alpine = Alpine
Alpine.start()
Alpine.js attributes
There are currently 15 attributes available.
- x-data
- x-init
- x-show
- x-bind
- x-bind class
- x-bind boolean
- x-text
- x-html
- x-if
- x-for
- x-on
- x-on modifiers
- x-model
- x-model modifiers
- x-ref
x-data
In Alpine, everything begins with the x-data
directive. x-data
specifies a block of HTML as an Alpine component. It provides reactive data for that component to use.
<div x-data="{ isValid: false }">
<!-- isValid is available only in this block -->
</div>
All element children have access to the properties defined in a x-data
directive. Even the nested x-data
components.
<div x-data="{ isValid: 'Yes' }">
<span x-text="isValid">
<!-- "Yes" -->
</span>
<div x-data="{ isSet: 'No' }">
<span x-text="isValid">
<!-- "Yes" -->
</span>
<div x-data="{ isValid: 'No' }">
<span x-text="isValid">
<!-- "No" -->
</span>
</div>
</div>
</div>
Methods defined in x-data
You may define the methods with different properties in the x-data
object.
<div x-data="{
open: false,
toggle() {
this.open = ! this.open
}
}">
<button @click="toggle()">Click To Toggle The Content</button>
<div x-show="open">
Toggle The Content...
</div>
</div>
x-init
The x-init directive allows you to intercept the initialization step of any Alpine element.
<div x-init="console.log('page loading begins')"></div>
In the preceding example, “page loading begins” will be output in the console before any more DOM updates are made.
You may also use it to fetch some JSON and store it in x-data
before the component is processed.
<div
x-data="{ users: [] }"
x-init="users = await (await fetch('/api/users')).json()"
>
<!-- your logic here -->
</div>
It is standalone. You can include x-init
in any element within or outside of an x-data
HTML block. As an example:
<div x-data>
<div x-init="console.log('component initialize here')"></div>
</div>
<div x-init="console.log('component initialize here too')"></div>
Evaluate the init() method automatically
If a component’s x-data
object contains an init()
method, it will be called automatically. As an example:
<div x-data="{
init() {
console.log('init method called automatically')
}
}">
<!-- your logic here -->
</div>
x-show
It allows you to show and hide DOM elements in an effective manner.
<div x-data="{ showElement: true }">
<div x-show="showElement">
This is visible...
</div>
</div>
<div x-data="{ showElement: false }">
<div x-show="showElement">
This is hidden...
</div>
</div>
v-bind
You can use x-bind
to set HTML attributes on elements. for example class, id, placeholder, etc.
<div x-data="{ placeholder: 'Input email' }">
<input type="email" x-bind:placeholder="placeholder">
</div>
You may use the shorthand syntax with colons (:) and avoid the v-bind
syntax for simplicity.
<input type="email" :placeholder="placeholder">
This is useful for binding classes.
<div :class="{ 'hidden': ! show }">
x-on
x-on is used to listen to the events.
<button x-on:click="alert('Hello World!')">Say Hi</button>
You may use the shorthand syntax: @
<button @click="alert('Hello World!')">Say Hi</button>
x-text
x-text
sets the text content of an element. It works similarly to JavaScript innerText.
<div x-data="{ firstName: 'John', lastName:'Doe' }">
<div>First Name: <strong x-text="firstName"></strong></div>
<div>Last Name: <strong x-text="lastName"></strong></div>
</div>
x-html
The innerHTML
property of an element is set by x-html
.
<div x-data="{ firstName: '<strong>John</strong>' }">
<div>First Name: <span x-html='firstName'></span></div>
</div>
x-model
The x-model
allows you to bind an input element’s value to Alpine data.
Here’s an example of how to use x-model
in Alpine to connect the value of a text field to Alpine data.
<div x-data="{ message: '' }">
<input type="text" x-model="message">
<span x-text="message">
</div>
The x-model is used for two-way binding, which means it “sets” as well as “gets” data. It not only changes the data, but it also reflects the change anytime the data changes.
<textarea x-model="message"></textarea>
<span x-text="message"></span>
In the same way you may use it with all kinds of HTML input elements. For details read the documentation about x-model
.
x-modelable
You can use x-modelable
to provide any Alpine property as an x-model
directive target.
<div x-data="{ number: 5 }">
<div x-data="{ count: 0 }" x-modelable="count" x-model="number">
<button @click="count++">Increment</button>
</div>
Number: <span x-text="number"></span>
</div>
The outer scope property “number” is now connected to the inner scope property “count,”.
x-for
The x-for
directive lets you iterate through a list to produce DOM elements. Here’s a simple example of how to use it to generate a colour list from an array.
<ul x-data="{ colors: ['Red', 'Orange', 'Yellow'] }">
<template x-for="color in colors">
<li x-text="color"></li>
</template>
</ul>
Specify unique keys for each x-for
iteration
<ul x-data="{ colors: [
{ id: 1, name: 'red' },
{ id: 2, name: 'blue' },
{ id: 3, name: 'green' },
]}">
<template x-for="color in colors" :key="color.id">
<li x-text="color.name"></li>
</template>
</ul>
Accessing indexes in x-for
If you need to get the index of each item in the iteration, use the ([item], [index]) syntax in [items] as follows:
<ul x-data="{ colors: ['Red', 'Orange', 'Yellow'] }">
<template x-for="(color, index) in colors">
<li>
<span x-text="index + ': '"></span>
<span x-text="color"></span>
</li>
</template>
</ul>
Iterating over a range in x-for
Alpine provides a concise syntax for looping n number of times.
<ul>
<template x-for="i in 6">
<li x-text="i"></li>
</template>
</ul>
x-transition
You may make seamless transitions between when an element is visible and when it is hidden using x-transition
directives.
<div x-data="{ open: false }">
<button @click="open = ! open">Toggle</button>
<span x-show="open" x-transition>
Hello 👋
</span>
</div>
Customizing duration with x-transition
With the .duration
modifier, you may specify the duration of a transition:
<div ... x-transition.duration.500ms>
The default duration is set to be 150 milliseconds when entering, and 75 milliseconds when leaving.
If you want to customise the durations for leaving and entering, do so as follows:
<div ...
x-transition:enter.duration.600ms
x-transition:leave.duration.500ms
>
Delay the transition
You may use the .delay
modifier to delay a transition as follows:
<div ... x-transition.delay.50ms>