Directive precedence in Alpine

Lots of people get caught out by the fact that Alpine evaluates each directive in a particular order. Let's look at the order it uses,

Published 7 months ago | Updated 7 months ago

Since Alpine doesn't have a virtual DOM and doesn't compile your templates, it evaluates a component's directives procedurally, in the order that they are defined.

Directive evaluation

When defining your directives on a component, the order does matter.

<div x-data="{ text: 'Hello' }">
    <p x-text="text" x-bind:style="color: red;"></p>

In the example above, our text will be set before the style attribute is updated. This could cause problems since you will see a flash of black, or whatever the default color is, before the x-bind:style directive is evaluated.

To counter this problem, you could swap the two directives around:

<div x-data="{ text: 'Hello' }">
    <p x-bind:style="color: red;" x-text="text"></p>

Now the x-bind:style is reached first, then our x-text directive is evaluated.

Another option would be adding x-cloak to the element, at the end.

<div x-data="{ text: 'Hello' }">
    <p x-text="text" x-bind:style="color: red;" x-cloak></p>

Now the <p> will be hidden (as long as you have the correct CSS) until Alpine has completely initialised the element.

If you're interested in the piece of code that handles all of the evaluation, you can find it here in the GitHub repository.

Got some feedback for me? Let me know on Twitter, or send me an email at