Introduction to AlpineJS Directives, Methods, and Properties

Learn about the AlpineJS directives, global methods, and magic properties.

AlpineJS has a syntax to define data and manipulate its state. These come in three forms:

  • Directive declaration syntax
  • Magic property syntax
  • Global method syntax

In this lesson, we’ll explore the main AlpineJS constructs and how to declare them using these syntaxes.

Directives

AlpineJS directives are AlpineJS attributes. Directives are like normal HTML attributes. But AlpineJS directives have an x- prepended to the directive name. For example, to define the data declaration directive, we use x-data.

AlpineJS has directives to define, manipulate, and present data and its state. This is why AlpineJS is very powerful for adding almost any type of interactivity to a website. We’ll use directives more than any other AlpineJS construct in our projects. So, it’s important to have a good grasp of them.

Magic properties

Magic properties allow us to access data and HTML elements. They also enable us to perform advanced actions on them. It gives us the freedom to use vanilla JavaScript in AlpineJS without limitations. Unlike directives, which are many, AlpineJS has only seven properties. Magic properties are prepended with a $ sign.

Global methods

Global methods in AlpineJS allow us to store and make data accessible in a global scope. They help us organize our projects into separate components and link them together with a single data source.

We access methods with Alpine.[methodName], where [methodName] is the method we want to use. Since there are only two of them(data and store), we only have Alpine.data and Alpine.store.