x-data
The x-data
directive is used to initialize a component with data. This is where you define the reactive state for your component.
In the example above, we use x-data="{ open: false }"
to define the initial state. Clicking the button toggles the open
state, showing or hiding the content.
<div x-data="{ open: false }"> <button @click="open = !open">Toggle Content</button> <div x-show="open">This content is toggled using Alpine.js</div> </div>
x-text
The x-text
directive is used to insert text content dynamically. It automatically escapes the content to prevent HTML injection.
Message:
In this example, x-text="message"
binds the content of the span
to the message
data property, which is updated as you type.
<div x-data="{ message: 'Hello, Alpine.js!' }"> <input x-model="message" type="text" placeholder="Type a message..."> <p>Message: <span x-text="message"></span></p> </div>
x-html
The x-html
directive allows you to insert HTML content directly. Be cautious as it does not escape content, which can lead to security risks.
Here, x-html
inserts the HTML content stored in htmlContent
. Notice how the content is rendered as HTML, not plain text.
<div x-data="{ htmlContent: '<strong>Bold HTML content</strong>' }"> <div x-html="htmlContent"></div> </div>
x-model
The x-model
directive binds data to an input element, keeping the data in sync with the element's value.
You typed:
With x-model
, the input's value is bound to the text
property. As you type, the value updates the text displayed below.
<div x-data="{ text: '' }"> <input x-model="text" type="text" placeholder="Type something..."> <p>You typed: <span x-text="text"></span></p> </div>
x-transition
The x-transition
directive provides easy animations for elements entering or leaving the DOM, such as during show/hide operations.
In this example, the x-transition
directive animates the element when it appears or disappears.
<div x-data="{ open: false }"> <button @click="open = !open">Toggle Animation</button> <div x-show="open" x-transition>This content is animated</div> </div>
x-for
The x-for
directive allows you to loop over an array and render elements for each item in the array.
In this example, x-for
loops through the items
array, rendering a list item for each element.
<div x-data="{ items: ['Alpine.js', 'TailwindCSS', 'JavaScript'] }"> <ul> <template x-for="item in items" :key="item"> <li x-text="item"></li> </template> </ul> </div>
x-bind:class
The x-bind:class
directive allows you to bind classes dynamically based on the state of your data.
Here, x-bind:class
adds or removes classes based on the error
state. Toggle the button to see the effect.
<div x-data="{ error: false }"> <button @click="error = !error">Toggle Error</button> <div :class="{ 'bg-red-500 text-white p-4 rounded': error, 'bg-green-500 text-white p-4 rounded': !error }"> <span x-text="error ? 'Error State' : 'Success State'"></span> </div> </div>