In this episode, we're diving into one of the most important features of Alpine.js: data binding. If you've ever worked with frameworks like Vue, you'll recognize the familiar pattern of using v-model
to bind form input values to your data — Alpine does the same thing with x-model
.
We'll start off by setting up a piece of data (like a name
property) using x-data
, then bind it to a text input using x-model
. You'll see in real time how typing into the input updates the internal data, and we'll also output the value next to the input so you can watch it change as you type.
Next, we'll take things a step further by showing how you can derive values from your data (like the length of your name as you type), and how to build a more realistic form that can be submitted. We explore intercepting form submission with Alpine's event modifiers like .prevent
, so the page doesn't refresh on submit, and we log out the submitted data — just like you might in a real app.
After that, we dive deeper into two-way data binding by adding a button that, when clicked, updates the name
value (like converting it to uppercase), and show how that change is instantly reflected both in the data and the input. This illustrates how any changes you make in the UI or the data stay perfectly in sync.
By the end of this video, you'll have a solid understanding of how to use x-model
for flexible and reactive forms in Alpine.js, how event handling works, and the power of two-way data binding. It's everything you need to connect your UI and your data with ease!