x-effect
is a useful directive for re-evaluating an expression when one of its dependencies change. You can think of it as a watcher where you don’t have to specify what property to watch, it will watch all properties used within it.
Version
Alpine 3.8
x-effect
<div>
is binding to HTML.
<!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 x-data="{ content: '<h1>Hello World</h1>' }">
<div x-effect="$el.innerHTML = content" />
</body>
</html>
Line 9
<body x-data="{ content: '<h1>Hello World</h1>' }">
<div x-effect="$el.innerHTML = content" />
</body>
x-data
: definecontent
variable with HTML includedx-effect
: use$el
to access the current element andinnerHTML
to write HTML to the element
Conclusion
x-effect
is a powerful directive. To simulatex-html
is one of the features ofx-effect