Alpine.data()
Register reusable component data factories.
What is Alpine.data()?
Alpine.data() registers a reusable component data factory globally. It's the key to building maintainable Alpine applications. Instead of writing inline objects inside x-data, you define your component logic in a function and give it a name.
When to Use
Use Alpine.data() whenever you have multiple components that share the same behavior – dropdowns, toasts, modals, etc. It also makes unit testing possible because you can export and test the plain function.
Basic Registration
Code
document.addEventListener('alpine:init', () => {
Alpine.data('counter', () => ({
count: 0,
increment() { this.count++ },
get double() { return this.count * 2 }
}))
})Usage in HTML
Code
<div x-data="counter">
<button @click="increment">+</button>
<span x-text="count"></span>
<span x-text="double"></span>
</div>Passing Parameters
Data factories can accept parameters, making them even more flexible.
Code
Alpine.data('modal', (initialOpen = false) => ({
open: initialOpen,
close() { this.open = false }
}))
// Usage: <div x-data="modal(true)">Best Practices
- Always call
Alpine.data()beforeAlpine.start(). - Use the
alpine:initevent to ensure Alpine is ready to receive registrations. - Keep data factories in separate JavaScript files and import them.
Can I access $refs inside Alpine.data()?
Yes, this.$refs works exactly like in inline data. The this context inside a data factory method refers to the component's reactive proxy.
Counter with reset
Count:
Double:
Helpful? Share this page!↑ Back to top