The translation of this document has been submitted to the official warehouse. For the latest document, please refer to the version in the official warehouse.

Alpine.js

Alpine. Js offers responsive and declarative features similar to those of larger frameworks like Vue or React at very low cost.

You can continue to manipulate the DOM and use Alpine. Js as needed.

Think of it as the JavaScript version of Tailwind.

Note: Alpine. Js’s syntax is almost entirely borrowed from Vue (with some extensions to Angular’s syntax). We thank them for their contributions to the Web world.

Install the Install

Using CDN: Add the following script to the end of your .

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js" defer></script>
Copy the code

That’s it. Alpine. Js will initialize itself.

In production environments, it is recommended to lock specific version numbers in links to avoid problems caused by changes in new versions. For example, the locked version is 2.8.0 (latest version):

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js" defer></script>
Copy the code

Using NPM: Install dependencies from NPM.

npm i alpinejs
Copy the code

And introduce it into your script.

import 'alpinejs'
Copy the code

Use this script for scenarios that require IE11 support.

<script type="module" src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"></script>
<script nomodule src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine-ie11.min.js" defer></script>
Copy the code

This writing uses module/nomodule mode, which allows modern browsers to automatically load module version dependencies, while proprietary compatible versions are automatically loaded in IE11 or other early browsers.

The Use of the Use

Dropdown/Modal pop-ups

<div x-data="{ open: false }">
    <button @click="open = true">Open Dropdown</button>

    <ul
        x-show="open"
        @click.away="open = false"
    >
        Dropdown Body
    </ul>
</div>
Copy the code

TAB Tabs

<div x-data="{ tab: 'foo' }">
    <button :class="{ 'active': tab === 'foo' }" @click="tab = 'foo'">Foo</button>
    <button :class="{ 'active': tab === 'bar' }" @click="tab = 'bar'">Bar</button>

    <div x-show="tab === 'foo'">Tab Foo</div>
    <div x-show="tab === 'bar'">Tab Bar</div>
</div>
Copy the code

This can also be used to preload HTML content from drop-down menus from the server while hovering over the mouse.

<div x-data="{ open: false }">
    <button
        @mouseenter.once=" fetch('/dropdown-partial.html') .then(response => response.text()) .then(html => { $refs.dropdown.innerHTML = html }) "
        @click="open = true"
    >Show Dropdown</button>

    <div x-ref="dropdown" x-show="open" @click.away="open = false">
        Loading Spinner...
    </div>
</div>
Copy the code

Learning to Learn

Currently, there are 14 commands available, as follows:

instruction describe
x-data Define a new component scope.
x-init The expression is run when the component is initialized.
x-show Controls the element based on the expression result (true or false)display: none;(Control module show/hide)
x-bind Sets the value of the current property to the result of the expression in the directive.
x-on Mount event listeners to elements. The expression is executed when the event is fired.
x-model Add bidirectional data binding to the current element. Keep input elements in sync with component data.
x-text andx-bindSimilar, but updated to the element’sinnerText.
x-html andx-bindSimilar, but updated to the element’sinnerHTML.
x-ref An easy way to get raw DOM elements outside the component.
x-if A value of false removes the element completely from the DOM. Need to be in<template>Tag.
x-for Create a new DOM node for each item in the array. Need to be in<template>Tag.
x-transition Instructions for adding classes to elements at various stages of transition (CSS Translation).
x-spread For better reuse, you can bind an object with the Alpine directive (as a key) to the element.
x-cloak This property is removed after Alpine initialization and can be used to hide the uninitialized DOM.

And 6 magic attributes:

Magic properties describe
$el Gets the DOM node of the root element.
$refs Gets the tags in the componentx-refDOM element.
$event Get the browser’s native “Event” object in the Event listener.
$dispatch Create a “CustomEvent” and use its internal.dispatchEvent()Method to distribute.
$nextTick After Alpine makes a reactive DOM update, it executes a given expression.
$watch Fires the given callback function when the listening component property changes.

Sponsors Sponsors

Want your Logo here?Send DM to Twitter

Community Projects

  • AlpineJS Weekly
  • Spruce (Status Management Framework/English)
  • Turbolinks Adapter
  • Alpine Magic Helpers
  • Awesome Alpine

Instruction Directives


x-data

For example:

X-data will define a new component scope. It tells the framework to initialize a new component with incoming data.

Similar to the data property in a Vue component.

Pull out the component logic

You can extract data (and behavior) from a reusable function:

<div x-data="dropdown()">
    <button x-on:click="open">Open</button>

    <div x-show="isOpen()" x-on:click.away="close">
        // Dropdown
    </div>
</div>

<script>
    function dropdown() {
        return {
            show: false.open() { this.show = true },
            close() { this.show = false },
            isOpen() { return this.show === true}}},</script>
Copy the code

Bundler users, note that Alpine. Js operates on functions that are in the global window. You need to declare the x-Data function on the window. For example window.dropdown = function () {} (because in Webpack, Rollup, Parcel, etc., function is mounted in module scope by default, not window).

You can also use object deconstruction syntax to mix up multiple data objects:

<div x-data="{... dropdown(), ... tabs()}">
Copy the code

x-init

For example: < div X-ray data = “{foo: ‘bar’}” x – init = “foo = ‘baz'” > < / div >

X-init will run the given expression at component initialization time.

If you want the code to be called after Alpine’s INITIAL DOM update (similar to VueJS’s Mounted () hook), you can pass in a callback function that will be called after the DOM operation is complete, for example:

x-init="() => { // we have access to the post-dom-initialization state here // }"


x-show

For example:

X-show controls the display: None element based on the result of the expression (true or false); (Control module show/hide)

x-show.transition

X-show. transition is a handy API for making CSS transitions easier to use with X-show.

<div x-show.transition="open">This will slip in/out in transition.</div>
Copy the code
instruction describe
x-show.transition Also slide in/out and scale (default: opacity, scale: 0.95, timing-function: cubic-bezier(0.4, 0.0, 0.2, 1), duration-in: 150ms, duration-out: 75 ms)
x-show.transition.in Just slide into
x-show.transition.out Just slip out of the
x-show.transition.opacity Use only fade-in and fade-out
x-show.transition.scale Just using zoom
x-show.transition.scale.75 Custom CSS scaling transforms totransform: scale(.75).
x-show.transition.duration.200ms Set the transition time of “in” to 200ms. The “out” action will be half that (100ms).
x-show.transition.origin.top.right Custom CSS conversion start position istransform-origin: top right.
x-show.transition.in.duration.200ms.out.duration.50ms Set different transition times for “in” and “out”.

Note: All transition modifiers can be combined. That is to say, it can be used this way (although it is too rude to use it this way) : x-show.transition.in.duration.100ms.origin.top.right.opacity.scale.85.out.duration.200ms.origin.bottom.left.opacity.scal e.95

Note: X-show will wait for the child element to complete out. If you want to skip this behavior, you can add the.immediate modifier:

<div x-show.immediate="open">
    <div x-show.transition="open">
</div>
Copy the code

x-bind

Note: Can be replaced with “:” shorthand syntax, for example :type=”…” .

For example:

X-bind sets the value of the current attribute to the result of the expression in the instruction. This expression can access all keys in the component data object and recalculate the results each time the data is updated.

Note: Attribute data bindings are recalculated only when dependent values are updated. The framework is smart enough to observe data changes and detect whether bindings care about those changes.

x-bindThe class attribute

X-bind behaves slightly differently when it completes the binding to the class attribute.

For a class, you can pass in an object with a key as the class name and a Boolean value to indicate whether the corresponding class should take effect.

For example:

In this example, the class “hidden” will only be valid if foo’s data attribute is true.

x-bindTo the Boolean attribute

X-bind supports Boolean attributes, which, like other value attributes, use variables or other expressions that result in true or false as conditions.

Such as:

<! -- set value: -->
<button x-bind:disabled="myVar">Click me</button>

<! MyVar == true: -->
<button disabled="disabled">Click me</button>

<! -- When myVar == false: -->
<button>Click me</button>
Copy the code

This adds or removes the disabled attribute when myVar is true or false, respectively.

The Boolean properties listed in the HTML Specification document are supported, for example: Disabled, Readonly, Required, Checked, hidden, selected, Open, and so on.

Note: If you need a false state to display your property, such as aria-*, use chained.toString() for the binding value. For example :aria-expanded=” isopen.toString ()” will preserve the property even if isOpen is true or false.

< SVG x-bind:view-box. Camel =”viewBox”>

The camel modifier is used to bind the attribute name of the equivalent camel notation. In the example above, the value of a viewBox will be bound to the viewBox property, which is represented as view-box.


x-on

Note: You can simply use the simplified “@” syntax, for example: @click=”…” .

X-on mounts an event listener to the declared element. When the event is triggered, the passed expression will be executed. You can use x-On any event that is available to the element of the directive. For a complete list of events, refer to the event reference documentation on the MDN.

If any data changes are made in the expression, the other element attributes bound to those data will be updated.

Note: You can also use JavaScript function names directly.

keydownThe modifier

You can specify specific buttons to listen for by adding the keyDown modifier to the X-ON: keyDown directive. Note that the modifiers are the kebab-cased version of the event. key value.

For example, Enter, escape, arrow-up, arrow-down

Note: You can also listen for mixed system modifiers like this: X-on :keydown.cmd.enter=”foo”

.awayThe modifier

For example:

When the.away modifier is present, event handlers are fired when the source is not themselves or their children.

This is useful for handling interactions in drop-down menus or modal boxes where the user clicks on a location outside of it to close.

Adding.prevent to the event listener will call the preventDefault method that triggers the event. In the example above, this means that the checkbox is not actually selected when the user clicks.

Adding.stop to the event listener will invoke the stopPropagation method that triggers the event. In the example above, this means that the click event does not bubble from this button to other divs. In other words, foo is not set to bar when the user clicks the button.

Self =”foo = ‘bar'”>

Adding.self to the event listener will cause the handler to be called only when $event. Target is the element itself. In the above example, this means that the handler function will not be called when the button click event bubbles on top of the

.

Window modifier for example:

Adding the.once modifier to the event listener ensures that the listener is called only once. This is especially useful for events that you only want to call once, such as requesting HTML fragments.

Adding.passive modifier to the event listener will make it passive, meaning preventDefault() won’t work. This can help deal with sliding performance issues on touch devices.

. Debounce Modifier For example:

The Debounce modifier allows you to “shock proof” the event handler. In other words, the event handler will wait some time after the last firing before firing again. The last call will be processed when the processor is ready.

The default “wait” time is 250 milliseconds.

If you want to customize it, you can specify it like this:

<input x-on:input.debounce.750="fetchSomething()">
<input x-on:input.debounce.750ms="fetchSomething()">
Copy the code

For example:

The camel modifier is used to mount an event listener equivalent to the camel script. In the example above, the expression will be executed when the eventName event is triggered.


x-model

X-model adds “two-way data binding” to an element. In other words, the value of the input element remains synchronized with the value of the data item in the component.

Note: THE X-Model can intelligently detect input, checkbox, Radio button, textarea, select and multi selects. His behavior and usage are the same as Vue’s.

Number modifiers for example:

The number modifier converts the input value to a numeric data type and returns the original value if it cannot be successfully converted.

. Debounce modifier for example:

The debounce modifier allows you to “guard” against updates to a value. In other words, the event handler will wait some time after the last firing before firing again. The last call will be processed when the processor is ready.

The default “wait” time is 250 milliseconds.

If you want to customize it, you can specify it like this:

<input x-model.debounce.750="search">
<input x-model.debounce.750ms="search">
Copy the code

x-text

X-text is very similar to X-bind, except that when the value in the attribute is updated, it updates the innerText of the element.


x-html

For example:

X-html is very similar to X-bind, except that it updates the innerHTML of the element when the value in the attribute is updated.

: Warning: Use only for trusted content, never display user content directly: Warning:

Dynamically rendering HTML from a third party source can be very vulnerable to XSS vulnerabilities.


x-ref

For example: < div x – ref = “foo” > < / div > < button x – on: click = “$refs. Foo. The innerText = ‘bar'” > < / button >

Structure: < div X-ray ref = “[ref name]” > < / div > < button x – on: click = “$refs. [ref name]. The innerText = ‘bar'” > < / button >

X-ref provides an easy way to get raw DOM elements outside the component. By setting the X-Ref attribute on the element, you can retrieve the DOM from the built-in object (the magic attribute) $refs and the tag’s refName in any event handling.

It helps you replace setting the id and then selecting it by document.querySelector anywhere.

Note: you can also bind a dynamic value to x-ref if you want.


x-if

For example:

Sometimes x-show can be awkward (it adds display: None to elements when the value is false), and x-if can actually remove elements from the DOM completely.

Note, however, that x-if can only be used in the
tag, because Alpine doesn’t use the virtual DOM. This implementation allows Alpine to keep it simple and use the real DOM directly for dynamic parts (magic).

Note: X-if requires a single root element in the
tag.

Note: When using Template in an SVG tag, you need to add Polyfill to run Alpine before initializing it.


x-for

Such as:

<template x-for="item in items" :key="item">
    <div x-text="item"></div>
</template>
Copy the code

Note: : Key binding is optional, but highly recommended, and is necessary for list rendering.

X-for can be used to create a new DOM node for each item in the array. This feature is very similar to v-for in Vue, which also needs to be used on the template tag, not a normal DOM element.

If you want to use an index in the current iteration, you can write it like this:

<template x-for="(item, index) in items" :key="index">
    <! You can use the index value index if necessary. -->
    <div x-text="index"></div>
</template>
Copy the code

If you need to access the original array object in an iteration, you can write:

<template x-for="(item, index, collection) in items" :key="index">
    <div>
        <! You can use the original collection value of the array if needed. -->
        <! -- Current item -->
        <div x-text="item"></div>
        <! Same as previous line -->
        <div x-text="collection[index]"></div>
        <! -- Previous item -->
        <div x-text="collection[index - 1]"></div>
    </div>
</template>
Copy the code

Note: X-for requires a single root element in the
tag.

Note: When using Template in an SVG tag, you need to add Polyfill to run Alpine before initializing it.

nestedx-for

You can nest x-for loops, but you must wrap one element around each loop, as follows:

<template x-for="item in items">
    <div>
        <template x-for="subItem in item.subItems">
            <div x-text="subItem"></div>
        </template>
    </div>
</template>
Copy the code

Scope iteration

Alpine supports the I in N syntax, which accomplishes the goal of iterating over a fixed range when n is an integer.

<template x-for="i in 10">
    <span x-text="i"></span>
</template>
Copy the code

x-transition

Such as:

<div
    x-show="open"
    x-transition:enter="transition ease-out duration-300"
    x-transition:enter-start="opacity-0 transform scale-90"
    x-transition:enter-end="opacity-100 transform scale-100"
    x-transition:leave="transition ease-in duration-300"
    x-transition:leave-start="opacity-100 transform scale-100"
    x-transition:leave-end="opacity-0 transform scale-90"
>.</div>
Copy the code
<template x-if="open">
    <div
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="opacity-0 transform scale-90"
        x-transition:enter-end="opacity-100 transform scale-100"
        x-transition:leave="transition ease-in duration-300"
        x-transition:leave-start="opacity-100 transform scale-100"
        x-transition:leave-end="opacity-0 transform scale-90"
    >.</div>
</template>
Copy the code

This example uses the classes provided in the Tailwind CSS.

Alpine provides six different Transition directives for implementing different classes at different stages of Transition in the show/hide state. These commands can be used with x-show and X-if.

These behaviors are completely consistent with VueJS transition instructions. It’s just a little bit clearer naming.

instruction describe
:enter This takes effect throughout the Enter phase
:enter-start Effect before the element is inserted, deleted 1 frame after the element is inserted
:enter-end 1 frame after the element is inserted (enter-startIs removed while) is in effect, is removed after the transition/animation is over |
:leave It takes effect during the entire Leave phase
:leave-start Frame 1 will be deleted immediately after the Leave transition is triggered
:leave-end After the Leave transition is triggered (leave-start1 frame is added and deleted at the end of the transition/animation. |

x-spread

Such as:

<div x-data="dropdown()">
    <button x-spread="trigger">Open Dropdown</button>

    <span x-spread="dialogue">Dropdown Contents</span>
</div>

<script>
    function dropdown() {
        return {
            open: false.trigger: {['@click'] () {this.open = true}},dialogue: {['x-show'] () {return this.open
                },
                ['@click.away'] () {this.open = false}}}},</script>
Copy the code

X-spread allows you to expand a reusable object, including the Alpine binding of elements.

The key of this object is an instruction (which can also include modifiers), and the value is a callback that Alpine executes.

Note: The following two points need to be noted about x-spread

  • When the instruction being expanded isx-forYou need to return an expression string in the callback, such as:['x-for']() { return 'item in items' }.
  • x-datax-initCannot be used in the “spread” object.

x-cloak

Cloak =”{}” x-cloak>

The X-Cloak property will be removed after Alpine initializes. This is very useful for hiding uninitialized DOM, and a typical way to do this through global style is as follows:

<style>
    [x-cloak] {
        display: none ! important;
    }
</style>
Copy the code

Magic Properties

With the exception of $el, magic properties are not available in X-data because the component is not initialized at that time.


$el

Such as:

<div x-data>
    <button @click="$el.innerHTML = 'foo'">Replace me with "foo"</button>
</div>
Copy the code

$EL is a magic property that gets the DOM node of the root component.

$refs

Such as:

<span x-ref="foo"></span>

<button x-on:click="$refs.foo.innerText = 'bar'"></button>
Copy the code

$refs is a magic property used to get native DOM elements in components. This will help you manually retrieve the original DOM elements if needed.


$event

Such as:

<input x-on:input="alert($event.target.value)">
Copy the code

$event is a magic property that accepts the browser’s native “event” object in the event listener.

Note: The $event attribute is valid only in DOM expressions.

If you need to use $event in a JavaScript function, you can do so:

<button x-on:click="myFunction($event)"></button>


$dispatch

Such as:

<div @custom-event="console.log($event.detail.foo)">
    <button @click="$dispatch('custom-event', { foo: 'bar' })">
    <! -- When clicked, console.log is triggered -->
</div>
Copy the code

About Event Propagation

Note that because of the event bubbling mechanism, you need to add the.window modifier when you need to intercept triggered events from nodes at the same level:

Such as:

<div x-data>
    <span @custom-event="console.log($event.detail.foo)"></span>
    <button @click="$dispatch('custom-event', { foo: 'bar' })">
<div>
Copy the code

The above example is an error demonstration and does not work because when a custom-event is triggered, it only propagates to the common ancestor, the parent div element.

Distribute to components

The same technique can also be used to communicate between components:

Such as:

<div x-data @custom-event.window="console.log($event.detail)"></div>

<button x-data @click="$dispatch('custom-event', 'Hello World! ')">
<! -- Console. log "Hello World!" when clicked . -- -- >
Copy the code

$dispatch is a shortcut to create a CustomEvent and distribute it using its internal.dispatchEvent(). There are many excellent use cases that use custom events to pass data between components. Refer to this document for more information about CustomEvents in the browser.

Note that the data placed in the second parameter of $dispatch(‘some-event’, {some: ‘data’}) is available on the new event via the ‘detail’ property: $event.detail.some. Attaching data for custom events to the.detail property is standard practice for CustomEvents in browsers. See this document (in English) for more information.

You can also use $dispatch() to trigger data updates for the X-Model binding. Such as:

<div x-data="{ foo: 'bar' }">
    <span x-model="foo">
        <button @click="$dispatch('input', 'baz')">
        <! When the button is clicked, 'x-model' will get a bubbling 'input' event and update foo to 'baz'. -->
    </span>
</div>
Copy the code

Note: The $dispatch attribute is valid only in DOM expressions.

If you need to use $dispatch in a JavaScript function, you can just do it:

<button x-on:click="myFunction($dispatch)"></button>


$nextTick

Such as:

<div x-data="{ fruit: 'apple' }">
    <button
        x-on:click=" fruit = 'pear'; $nextTick(() => { console.log($event.target.innerText) }); "
        x-text="fruit"
    ></button>
</div>
Copy the code

$nextTick is a command that executes a given expression after you make a responsive DOM update in Alpine. This is useful when you need to interact with THE DOM state after a data update.


$watch

Such as:

<div x-data="{ open: false }" x-init="$watch('open', value => console.log(value))">
    <button @click="open = ! open">Toggle Open</button>
</div>
Copy the code

You can “listen” on a component property using the $watch magic method. In the example above, when the button is clicked and open is changed, the callback function you provided is called, console.log new value.

Security-related Security

If you find a security breach, email us at [email protected].

Alpine relies on a custom implementation of the Function object to run the directive. Although safer than Eval (), this method is not available in some environments, such as the restricted Content Security Policy/CSP used by Google Chrome App.

If you’re working with sensitive data on a site that uses Alpin, you’ll need to set up CSP to include safe-Eval. Proper security policies can help protect users’ private data.

Because policy Settings apply to all scripts on the page, it’s important to check for other external dependencies that the page introduces to prevent them from opening XSS vulnerabilities and injecting malicious code through EVAL () DOM modification.

V3 Roadmap Roadmap

  • fromx-refMigration torefTo be consistent with Vue?
  • newAlpine.directive()
  • newAlpine.component('foo', {... })(by__init()Magic method)
  • Distribute Alpine’s “loaded”, “transition-start” and other events (#299)?
  • removex-bind:class="{ 'foo': true }"Syntax for using objects (and arrays) in# 236And increase instyleSupport for using objects in
  • To optimize thex-forIs responsive effect (# 165)
  • Added “deep watching” support (#294)
  • increase$elA shortcut
  • Modify the@click.away@click.outside?

The permit License

Copyright © 2019-2020 Caleb Porzio and All Contributors to the Warehouse

Open source under the MIT LICENSE, see license.md for details.