LoginSignup
5
2

More than 1 year has passed since last update.

Alpine.jsのライフサイクルは少ない

①初期化(x-init)

x-initを使えば、読み込み時に最初に行う処理を定義することができます。

<button x-init="console.log('Im initing')">

ただし、以下のコードでは注意が必要です。
x-initは最初に設定した値を上書きするので、下記のコードではx-dataのcounter: 0はx-initで上書きされます。

<div x-data="{counter: 0}">
    <button @click="counter++">ボタン</button>
    <div x-text="counter"></div>
</div>

See the Pen Untitled by gorimatyan (@gorimatyan) on CodePen.

 ↑ x-initでcounterが10になっている

②プロパティの監視(x-effect)

これはReactのuseEffectみたいなやつです。
x-effect内で定義した関数の中に使われているプロパティに変更があるたびに実行されます。

<div x-data="{ open: false }" x-effect="console.log(open)">

この場合はopenプロパティに変更があるたびにx-effectの中のconsole.log(open)が実行されます。

③プロパティの監視($watch)

x-effectとは違って、監視する変数を指定できます。

<div x-data="{ open: false }" x-init="$watch('open', value => console.log(value))">

この場合はopenプロパティに変更があるたびにconsole.log(open)が実行されます。

$watchは更新前の値も取得できる。

<div x-data="{ open: false }" 
     x-init="$watch(
        'open', 
        (value, oldValue) => console.log(value, oldValue))
">                ↑これが変更前の値

    <button @click="open = ! open">Toggle Open</button>
</div>

$watchのコールバック関数の中の第二引数(oldValue)を定義すれば、更新前の値を取得することができる。

まとめ

とりあえずこの3つ押さえとけば何でも作れる(たぶん)

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2