Sometimes, we want to wait until after Alpine has completely finished rendering to execute some code. We can use $nextTick
in x-init
.
Version
Alpine 3.8
x-init
After Alpine has finished rendering, console.log
the element’s value.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
</head>
<body>
<input
x-data="{ message: 'Alpine Rocks' }"
x-model="message"
x-init="$nextTick(() => console.log($el.value))"
/>
</body>
</html>
Line 10
<input
x-data="{ message: 'Alpine Rocks' }"
x-model="message"
x-init="$nextTick(() => console.log($el.value))"
/>
x-data
: define a variable for two-way data binding on<input>
x-model
: two-way data binding the input value to a variablex-init
: run expressions on initialization phase of the component$nextTick
: run expressions after rendering to get the value of the element$el
: retrieve the current DOM element
Conclusion
x-init
+$nextTick
ensures that Alpine has finished rendering