DEV Community

Niyaz
Niyaz

Posted on

Alpine.js, exploring in real world applications

Alpine is a minimal javascript library for composing behavior directly in HTML markup.

Alpine was known as “project-x”, a nod to it’s past.
Creator Caleb Porzio (Creator of Alpine.js, Laravel Livewire) has kept much of the syntax is like Vue.js.

Okay, Lets start..

To use:

From a script tag into head tag:
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
Enter fullscreen mode Exit fullscreen mode
As a module:
`npm install alpinejs` or `yarn alpinejs`
Enter fullscreen mode Exit fullscreen mode
import Alpine from 'alpinejs'
window.Alpine = Alpine
Alpine.start()
Enter fullscreen mode Exit fullscreen mode

Alpine has collection of 15 attributes, 6 properties, and 2 methods.

x-data, x-bind, x-on, x-text, x-if, x-for, x-ref, x-html...

Please check the docs here, https://alpinejs.dev

Creating simple component (x-data);

All we need to do is add the x-data attribute to any element like below, Thats all.

<div x-data="{ title: 'Hello Alpine..' }">
<p x-text="title"></p>
<button @click="title='Alpine rocks'">Change Title</button>
Enter fullscreen mode Exit fullscreen mode
On Modular approach:
On main.js
import Alpine from 'alpinejs';
window.Alpine = Alpine

import pageSidebar from './components/PageSidebar.js';
window.sidebarApp = pageSidebar;

Alpine.start()
Enter fullscreen mode Exit fullscreen mode
On components/PageSidebar.js
export default () => {
  return { 
      data: null,
      init() {
          console.log('sidebar component');
      },
      // methods
      // ......
  }
}
Enter fullscreen mode Exit fullscreen mode
on Html Markup:
<div x-data="sidebarApp()">
......
</div>
Enter fullscreen mode Exit fullscreen mode

explore more details here : https://alpinejs.dev/start-here

Thats All. Hope you get idea. Thanks for reading.

Top comments (0)