Alpine.js - Technological watch

Learn what is Alpine.js in less than 5 minutes !
Tuesday, October 12, 2021

What kind of framework is Alpine.js ?

Alpine.js is a super easy lightweight javascript framework inspired from Vue.js, used for website to make tiny interactions with the user.

The framework brings a different approach than a traditional javascript code. Instead of manipulating the DOM, we manipulate a state (group of variables), and the framework will automatically refresh the HTML part for us.

The framework is popular ; it has 18.7K stars on github, and is lightweight (33.94 KB).

The framework structure

Attributes

The framework philosophy is about to add attributes in the HTML tags. The attributes look like <div x-myAttribute="dataHere"></div>

Example:

<div>
Copyright ©
<span x-text="new Date().getFullYear()"></span>
</div>

This would print Copyright © 2022.


We can declare variables like this:

<div x-data="{ open: false }">...</div>

Or listen to events like this:

<button x-on:click="open = !open">Toggle</button>

Then, you can use all these directives together:

<div x-data="{ open: false }">
<button x-on:click="open = ! open">Toggle alert</button>
<div x-show="open">My alert is showed !</div>
</div>

Of course, we can show or hide HTML parts, or making loops on arrays !

Attributes are very powerful and are available here: https://alpinejs.dev/directives/data.

Properties

Properties are pre-injected global alpine variables beginning with a $. Properties can be alpine variables or alpine functions.

It can be used for more complex operations.

We can find a $refs variable, which refers to the current reference in the DOM.

<div x-init="$refs.button.remove()">
<button x-ref="button">Remove Me</button>
</div>

Methods

Methods are part of alpine framework which can be used in script tags, which can help you to keep a proper HTML is it is becoming too big.

<div x-data="dropdown">...</div>
<script>
Alpine.data("dropdown", () => ({
open: false,
toggle() {
this.open = !this.open;
},
}));
</script>

My opinion

Alpine.js is a great solution for small application which don’t need a full-stack JavaScript framework like Vue, React or Angular. Alpine is very similar and keep the simpleness of Vue.

The documentation is light but easy to read, easy to understand and easy to learn. Alpine gives you all the keys to launch your application !

If you want to add only few user interactions or animations without the fear of making JavaScript too much complex to understand, Alpine.js is a perfect tool for you !


Recommended articles