點燈坊

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

Using x-data with Getter

Sam Xiao's Avatar 2022-02-11

JavaScript Getter is handy when the sole purpose of a method is to return data based on another state. Think of them like Computed Property in Vue.

Version

Alpine 3.8

TailwindCSS

getter000

Use Getter directly in HTML just like TailwindCSS.

<!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="{
    name: 'World',
    get greeting() {
      return `Hello ${ this.name }`
    }}"
  >
    <span x-text="greeting" />
  </body>
</html>

Line 9

<body
  x-data="{
  name: 'World',
  get greeting() {
    return `Hello ${ this.name }`
  }}"
>
  • get greeting() : use Getter to for computed property
  • x-text : bind to Getter directly

Vue

getter000

  • It may be too verbose to use Getter in HTML
  • We can use Getter in JavaScript just like Vue
<!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>
    <script>
      let helloWorld = {
        name: "World",
        get greeting() {
          return `Hello ${this.name}`;
        },
      };
    </script>
  </head>
  <body x-data="helloWorld">
    <span x-text="greeting" />
  </body>
</html>

Line 9

let helloWorld = {
  name: "World",
  get greeting() {
    return `Hello ${this.name}`;
  },
};

Implement getter on helloWorld Object. It’s more readable in JavaScript.

Line 17

<body x-data="helloWorld">
  <span x-text="greeting" />
</body>
  • x-data : bind helloWorld Object to x-data directive
  • x-text : bind to getter directly

Svelte

getter000

We can also use function to implement Getter just like Svelte.

<!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>
    <script>
      let greeting = (x) => `Hello ${x.name}`;
    </script>
  </head>
  <body x-data="{ name: 'World' }">
    <span x-text="greeting($data)"></span>
  </body>
</html>

Line 12

<body x-data="{ name: 'World' }">
  <span x-text="greeting($data)"></span>
</body>
  • Define data in x-data directive
  • Pass $data to greeting. $data is a proxy of data in x-data

Line 9

let greeting = (x) => `Hello ${x.name}`;
  • Since $data is a proxy, we can use x.name to access name state
  • We don’t have to use this to access data so that we can use arrow function instead of function expression

Conclusion

  • Alpine’s Getter is not cached like Vue’s computed property

Reference

Alpine, Getters