In this Alpine js tutorial we will see x-bind with bind classes, binding style and bind image with alpinejs 2 and alpinejs 3. x-bind is similar like vuejs v-bind data if you familiar with vuejs then it is easy to understand. x-bind allows you to set HTML attributes on elements based on the result of JavaScript expressions. x-bind is use for bind classes , Special behavior in css , Binding styles in last you can aslo bind image.
Tool Use
Tailwind CSS 2.x
Alpine Js 3.x or 2.x
Syntax
we will use x-bind to set the age value of an input value and class like x-bind:class , x-bind:value.
<div x-data="{ age: 18, bigText:'text-2xl font-bold' }">
<label for="age" x-bind:class="bigText">Age</label>
<input type="text" name="age" x-bind:value="age" class="w-full p-2 border border-gray-300 focus:outline-none "
placeholder="Enter Your Age">
</div>
Shorthand syntax
we can also use x-bind:class , x-bind:value to :class or :value to short code
<div x-data="{ age: 18, bigText:'text-2xl font-bold' }">
<label for="age" :class="bigText">Age</label>
<input type="text" name="age" :value="age" class="w-full p-2 border border-gray-300 focus:outline-none "
placeholder="Enter Your Age">
</div>
👉 Alpine js x-data Tutorial by Example
Example 1
Binding with Classes.
You can write short class code using x-bind to classes
<div x-data="{ inputClass: 'w-full p-2 border border-gray-300 focus:outline-none' }" class="space-y-2">
<input type="text" :class="inputClass" name="name" placeholder="Name">
<input type="text" :class="inputClass" name="email" placeholder="Email">
<input type="text" :class="inputClass" name="age" placeholder="Age">
</div>
Example 2
Binding with Style.
<div x-data="{ styles: { background: 'blue', width:200, height:200, padding:'4rem'}}">
<div :style="styles">
Style Binding
</div>
</div>
Example 3
Binding with Image. you can use this methods both alpine v3 and alpine 2
<div x-data="{ image: 'https://picsum.photos/200/300?grayscale' }">
<img :src="image" alt="image">
</div>
Binding with alpine js v2
<div x-data="myImage()">
<img :src="image" alt="image">
</div>
<script>
function myImage() {
return {
image: 'https://picsum.photos/200/300?grayscale'
}
}
</script>
Binding with alpine js v3
<div x-data="myImage">
<img :src="image" alt="image">
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('myImage', () => ({
image: "https://picsum.photos/200/300?grayscale"
}))
})
</script>
Example 4
you can also bind in condition like ternary and or with classes. you can write short class code using x-bind
<div x-data="{ isOpen: false }">
<button @:click="isOpen = ! isOpen"> Dropdown</button>
<div :class="isOpen ? '' : 'hidden'">
Dropdown content...
</div>
</div>
To better using x-show
<div x-data="{ isOpen: false }">
<button x-on:click="isOpen = ! isOpen"> Dropdown</button>
<div x-show="isOpen">
Dropdown content...
</div>
</div>