點燈坊

失くすものさえない今が強くなるチャンスよ

Using x-effect to Simulate x-html

Sam Xiao's Avatar 2022-02-11

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

effect000

<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 : define content variable with HTML included
  • x-effect : use $el to access the current element and innerHTML to write HTML to the element

Conclusion

  • x-effect is a powerful directive. To simulate x-html is one of the features of x-effect

Reference

Alpine, x-effect