Directive precedence in Alpine
This post was published 4 years ago. Some of the information might be outdated!
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>
</div>
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>
</div>
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>
</div>
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.