Directive precedence in Alpine

alpinejs
Table of Contents

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.

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

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:

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.

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.

Enjoyed this post or found it useful? Please consider sharing it on Twitter.