Alpine.js Core Directives

- Andrés Cruz

En español
Alpine.js Core Directives

Alpine is a framework that, having such a simple, clean and abstract structure, its magic is better understood from practice.

The structure of Alpine.js is based on some directives and methods to perform the different reactive and declarative operations that Alpine.js allows us.

Attributes or directives

All these attributes are, as their name indicates, HTML attributes that must be defined in HTML elements such as DIV, P, SECTION, etc. And that is interpreted by Alpine to be able to create the component.

Logically, each of these attributes has a particular purpose that will be introduced below:

  • x-data To initialize the variables with which we are going to work.
  • x-show To show or hide an element based on a boolean condition.
  • x-init By means of a function, it allows initializing variables, calling functions, etc; whatever procedure you want to do before building the component.
  • x-bind To be able to use attribute binding.
  • x-if Allows you to perform boolean conditions to render or remove HTML content to which it is assigned.
  • x-show Allows you to hide or show an HTML based on a boolean condition.
  • x-model Allows you to bind (bidding) a form field with a variable.
  • x-text Allows you to print the text of a variable.
  • x-html Allows you to render HTML content in a component.

Magical methods

At Alpine, we have some magic methods to perform different operations; they differ from attributes in that they are functions, functions that implement specific functionality of the framework; among the main ones we have:

  • $watch() To watch for changes in variables and execute a process.
  • $el() To obtain the reference to the element as if it were a JS selector.
  • $refs() Get reference to any HTML element as if it were a JS selector.
  • $store() Store data globally and accessible to any Alpine component on a page.
  • $nextTick() This is a magic property that allows a block of JavaScript to be executed after Alpine has done its reactive DOM updates.

Events

For the use of events in Alpine, we can use the prefix of x-on or @; for example, for the click event:

  1. x-on:click
  2. @click

Now, we are going to know the events that can be used in Alpine.js; All these events allow you to invoke a function as it is the basic operation that you have from vanilla JavaScript:

  • @click Click event on an element.
  • @keyup Keyboard event.
  • @change Event used to change the state or selection of the checkboxes, radios, select, among others.

As for the events that we can use, they are the same as the JavaScript API:

https://www.w3schools.com/js/js_events.asp

 

Este tutorial forma parte de mi libro sobre Alpine.js

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.