Description: `Alpine.data()` allows you to define named, reusable data structures and associated behaviors (methods, initial state). This is a powerful feature for promoting DRY (Don't Repeat Yourself) principles by encapsulating component logic that can be easily applied to multiple `x-data` instances across your application.
You define a reusable component "blueprint" using `Alpine.data()`:
document.addEventListener('alpine:init', () => {
Alpine.data('reusableName', (param1, param2, ...initialArgs) => ({
// Initial reactive properties
property1: 'defaultValue',
property2: param1, // Use passed parameters
itemCount: 0,
// Lifecycle hook (optional)
init() {
// Code to run when the component initializes
// 'this' refers to the component instance
console.log(`Component initialized with param1: ${this.property2}`);
// You can also access other Alpine magic properties like this.$el
},
// Methods (behaviors)
incrementCount() {
this.itemCount++;
},
anotherMethod(value) {
this.property1 = value;
console.log(`Called anotherMethod with ${value}`);
}
}));
});
To use this reusable logic in your HTML, you reference it by name in an `x-data` attribute. You can also pass arguments to its constructor function:
<!-- Instance 1 with arguments -->
<div x-data="reusableName('customValue', 123)">
<p>Property 2: <span x-text="property2"></span></p>
<p>Count: <span x-text="itemCount"></span></p>
<button @click="incrementCount">Increment</button>
<button @click="anotherMethod('new text')">Set Property 1</button>
</div>
<!-- Instance 2 with different arguments or defaults -->
<div x-data="reusableName('anotherCustomValue', 456)">
<!-- ... similar structure ... -->
</div>
Each `div` with `x-data="reusableName(...)"` gets its own independent instance of the defined data and methods. Changes in one instance do not affect others.
Status: