In this Alpine js tutorial we will see x-data . The x-data declares a new component scope. It tells the framework to initialize a new component with the data object. Alpine js start with x-data let see alpine js some Example.
Example 1
first we need to create x-data in div or any html tag to start Alpine js components . then we can define object like JavaScript and give value to object to display object we use x-text it will print output
<div x-data="{message: 'Alpine js is Awesome'}">
<p x-text="message"></p>
</div>
output:
Alpine js is Awesome
Example 2
you can use other html tag it work all of them you can use with div,h1,p,ul, any other tag will work . but for right way use should x-data with div Tag it is right way
<h1 x-data="{hOne: 'h1 one is working'}" x-text="hOne"></h1>
<p x-data="{pTag: 'p tag is working'}" x-text="pTag"></p
Example 3
Don't Do ❌
You should not print outside of div tag x-data start with open close tags if you call outside of tag it will not work
<div x-data="{message: 'Alpine js is Awesome'}">
<h2>Apline js</h2>
</div>
<p x-text="message"></p>
Do ✅
<div x-data="{message: 'Alpine js is Awesome'}">
<h2>Apline js</h2>
<p x-text="message"></p>
</div>
Example 4
if you have many filed you can display like 👇 this . or you can display better way
To Do This 👇
<div x-data="{
name: 'larainfo',
email:'[email protected]',
number : 99999999,
pincode:666656
}">
<ul>
<li x-text="name"></li>
<li x-text="email"></li>
<li x-text="number"></li>
<li x-text="pincode"></li>
</ul>
</div>
Better way 👇
if you have many object you can simply put into function in script tags it is easy to read and clean code
<body>
<div x-data="userDetail()">
<ul>
<li x-text="name"></li>
<li x-text="email"></li>
<li x-text="number"></li>
<li x-text="pincode"></li>
</ul>
</div>
</body>
<script>
function userDetail() {
return {
name: 'larainfo',
email: '[email protected]',
number: 99999999,
pincode: 666656
}
}
</script>