What is x-data
in Alpine.js?
x-data
is one of the core directives in Alpine.js. It defines a local state (data and methods) for a DOM element. This state is reactive, meaning when data changes, the view (HTML) automatically updates.
Think of x-data
as:
A JavaScript object that lives inside your HTML.
It contains variables (data) and functions (methods) that control the behavior of the element and its children.
Here's an example:
In this example, we've defined a div element with an x-data attribute that defines an object with a single property called "message". We've also added an h1 element with an x-text attribute that displays the value of the "message" property.
When you load this page, you'll see the text "Hello, World!" displayed on the screen.