We can also provide init()
in the x-data
Object, and it will be called automatically without the x-init
directive.
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
init()
The same result uses the init()
method instead of the x-init
directive.
<!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',
init() { $nextTick(() => console.log($el.value)) }
}"
x-model="message"
/>
</body>
</html>
Line 10
<input
x-data="{
message: 'Alpine Rocks',
init() { $nextTick(() => console.log($el.value)) }
}"
x-model="message"
/>
init()
: if thex-data
Object of a component contains aninit()
method, it will be called automatically withoutx-init
directive
Conclusion
init()
may be useful in some situation