This is an ever-growing list of tips, tricks, and gotchas picked up while working with Alpine.js.

An image of a mountain top Image by Stephan Seeber on Pexels

1. Why Alpine.js?

Alpine.js:

  • Syntax like Vue or Angular
  • Doesn’t have virtual DOM (thus no build steps like Vue/Angular)
  • Use it when JS should be kept very minimal
  • Declarative code (like Vue et al.)
  • It comes with its own dev tools
  • 4kb gzipped

The purpose of the project is described on its Github page:

Think of it like Tailwind for JavaScript.

2. How to install and get started with Alpine.js?

Two ways to install Alpine.js:

  • using a CDN
  • using npm

With the CDN, we specify the script tag (inside the head tag), like this:

<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js" defer></script>

With npm, we run the install command:

npm install alpinejs

And then we can include it in the script: import 'alpinejs'.

3. Directives and magic properties in Alpine

There are 14 directives, each starting with x-, and ending with one of the following: data,init,show,bind,on,model,text,html,ref,if,for,transition,spread,cloak.

There are also 6 magic properties:

  • $el
  • $refs
  • $event
  • $dispatch
  • $nextTick
  • $watch

If you know how to use Vue, the above syntax will feel quite familiar. Alternatively, you can read the descriptions for these directives and magic properties on the Alpine.js Github page.

4. Dropdown

<div x-data="{ open: false }">
    <button @click="open = true">Open Dropdown</button>

    <ul
        x-show="open"
        @click.away="open = false"
    >
        Dropdown body
    </ul>

</div>

5. To be continued…

To be continued…