Dev Alpine.js Field Guide

Alpine.js Field Guide

Below are examples of the Alpine.js directives we use to build storefront components. While these examples are self-contained and include all the data they need to run, it is worth mentioning that any data we make available in our API and any JavaScript you might dream up can be utilized in the same way.

For a full list of Alpine.js directives including shortcuts and detailed examples, please see the official documentation here: Alpine.js Docs

x_text

Sets the text that should be displayed for an element.
1
2
3
<div x-data="{ OS: navigator.platform }">
  Current OS: <span x-text="OS"></span>
</div>

x_on

Allows you to run javascript any time a dom event is fired. this lighthearted example makes heavy use of the click event, but keyboard clicks and other events can be captured as well.
1
2
3
4
5
6
7
8
9
<div x-data="{ text: 'Buffalo ' }">
  <button x-on:click="text = 'Buffalo '">
    Reset
  </button>
  <button x-on:click="text += 'buffalo '">
    Add text:
  </button>
  <label x-text="text"></label>
</div>

x_show

Controls when an html element is displayed. you can dynamically show and hide parts of your component by assigning a variable to x-show.
1
2
3
4
5
6
<div x-data="{ show: true }">
  <button x-on:click="show=!show">
    Toggle text:
  </button>
  <label x-show="show">Hello Alpine!</label>
</div>

x_model

Allows you to bind an input field to a variable. this binding is two-way, so changing the input field will update this variable, and changing this variable will overwrite and update the field.
1
2
3
4
<div x-data="{ example_text: 'Type here...' }">
  <input x-model="example_text" />
  <h2 x-text="example_text"></h2>
</div>

x_for

Dynamically generates markup based on elements in a javascript array. it must be declared in a <template> tag and that <template> must have only one child element (though that child can have as many elements as you please).
1
2
3
4
5
6
<ul x-data=
  "{ list: ['Free', 'Standard', 'Overnight'] }">
  <template x-for="rate in list">
    <li x-text="rate"></li>
  </template>
</ul>

x_bind

Allows you to bind any html attribute to the result of a javascript expression.
1
2
3
4
5
6
7
8
<div x-data="{ fill: 0 }">
  <button x-on:click="fill += 10">
    Buy now!
  </button><br>
  Sales:
  <meter x-bind:value="fill" min="0" max="150">
  </meter>
</div>
Anatomy of a Storefront Component Rate Calculator API