Livewire 親子のコンポーネントについて、親のプロパティを更新するには?LiveRelationトレイト編 oyako3

ショコラ
ショコラ

Livewire 親子のコンポーネントについて、親のプロパティを更新するには?LiveRelationトレイト編 oyako3

何度か Livewire 親子コンポーネントについて記事をかきました。
「子コンポーネントを更新した時に、子コンポーネントからイベントを発行して(emit)、親コンポーネントのプロパティを更新する方法」はありましたが、
どうしても親コンポーネントから子コンポーネントの値を参照できないのは納得できません。
そこで今回は、LiveRelationトレイト というものを作りましたので、これを説明しようと思います。
これを使えば、livewireタグ に
「bind=”{親のプロパティ}:{子のプロパティ}”」
の属性を追加するだけで、子のプロパティに変更があれば親のプロパティを更新するようになります。

トレイトにするかクラスにするか悩みましたが、トレイトですね。
https://laravel-livewire.com/docs/2.x/traits

もっさん先輩
もっさん先輩

手順

Laravel と Livewire をインストールして、LiveRelationトレイトを使う手順。

  1. プロジェクト名(oyako3)を決めて以下のコマンドを実行します。
curl -s https://laravel.build/oyako3 | bash

インストール時にプロジェクト名のディレクトリが作成されます。

  1. インストールの最後に sudo でパスワードの入力を求められます。

↓下のメッセージが表示されてインストールは終わります。

Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them

Get started with: cd oyako3 && ./vendor/bin/sail up
  1. sail のエイリアスを定義します。
echo "alias sail='[ -f sail ] && sh sail || sh vendor/bin/sail'" >> ~/.bashrc
source ~/.bashrc

Laravel のインストールはここまで。

  1. 「sail up」でコンテナを起動します。
cd oyako3 && sail up -d
  1. ララベルのトップディレクトリで、Livewireパッケージ をインストールします。
sail composer require livewire/livewire
  1. Livewire のクラスとビューを作成するため、ディレクトリを作成します。
mkdir app/Http/Livewire/
mkdir resources/views/livewire
  1. 今回のメイン。LiveRelationトレイト を作成します。

配置先:app/Http/Livewire/LiveRelation.php

<?php
namespace App\Http\Livewire;
use Livewire\LivewireManager;
use Livewire\LifecycleManager;
use Livewire\Component;
trait LiveRelation
{
  public string $bind = ''; // 『親のプロパティ:自分のプロパティ』で関連付ける。
  public string $name = ''; // コンポーネント識別名
  public bool $livedata = true; // メソッド呼び出し時のパラメーターに LiveData を自動で付ける。

  public function boot() {
    LiveData::$current_component = $this;
  }

  public function isChild($childId) {
    return collect($this->previouslyRenderedChildren)->pluck('id')->search($childId);
  }

  public function dehydrate() {
    if ('' != $this->bind) {
      $vars = [];
      foreach (explode(',',$this->bind) as $bind) {
        [$property,$self_property] = explode(':',str_repeat($bind.':',2));
        $method = 'get'.\Str::studly($self_property);
        if (method_exists($this,$method))
          $value = $this->{$method}();
        else if (property_exists($this,$self_property))
          $value = $this->{$self_property};
        else
          continue;
        $vars[$property] = $value;
      }
      if ([] !== $vars)
        $this->emitParent('updateBindings',$vars);
    }
  }

  protected function getListeners() {
    return array_merge(parent::getListeners(),['updateBindings','syncBindings','setProperties'],
      ['set'.\Str::studly($this->id) => 'setProperties'],
      ('' != $this->name) ? ['set'.\Str::studly($this->name) => 'setProperties']:[]);
  }

  public function updateBindings($vars) {
    foreach ($vars as $property => $value) {
      $method = 'update'.\Str::studly($property);
      if (method_exists($this,$method))
        $this->{$method}($value);
      else if (property_exists($this,$property))
        $this->{$property} = $value;
    }
  }

  public function syncBindings(LiveData $data) {
    if ('' != $this->bind) {
      foreach (explode(',',$this->bind) as $bind) {
        [$property,$self_property] = explode(':',str_repeat($bind.':',2));
        $this->$self_property = $data->getParent()[$property];
      }
    }
  }

  public function setProperties(LiveData $data) {
    foreach ($data() as $property => $value)
      $this->{$property} = $value;
    $data()->dirty = false;
  }

  public function emitSet(string $key, LiveData $data) {
    if (!in_array($key,[$this->id,$this->name]))
      $this->emit('set'.\Str::studly($key),$data);
  }

  public function emitDirtySet(LiveData $data) {
    collect($data)
      ->filter(fn($component) => $component->dirty)
      ->each(fn($component) => $this->emitSet($component['id'],$data));
  }

  public function emitFind($key, $event, ...$params) {
    $this->emit('emitFind',$key,$event,...$params);
  }

  public function emitParent($event, ...$params) {
    $this->emit('emitParent',$this->id,$event,...$params);
  }

  public function mountLivewireTag(string $livewire_tag,$target='body') {
    $this->emit('createComponent',render_blade($livewire_tag),$target);
  }

  public function mountComponent(string $name,array $params=[],$target='body') {
    $this->emit('createComponent',\Livewire\Livewire::mount($name,$params)->html(),$target);
  }

  public function removeComponent(string $key = null) {
    $key ??= $this->id;
    $this->emit('removeComponent',$key);
  }

  public function createComponent(string $name,array $params) {
    $id = str()->random(20);
    return LifecycleManager::fromInitialRequest($name,$id)
      ->boot()
      ->initialHydrate()
      ->mount($params)
      ->instance;
  }

  public function renderComponent(Component $component,string $target='body') {
    $response = LifecycleManager::fromInitialInstance($component)
      ->renderToView()
      ->initialDehydrate()
      ->toInitialResponse();
    $this->emit('createComponent',$response->html(),$target);
  }
}

LiveRelation のポイント
①LiveRelation の bootメソッド で、LiveData の カレントコンポーネント を設定するようにしました。
②emitFindメソッドを追加しました。JavaScript の emitFind を使います。
③emitParentメソッド を追加しました。JavaScript の emitParent を使います。
④mountLivewireTag、mountComponent、removeComponentメソッド を追加しました。
⑤createComponent、renderComponentメソッド を追加しました。

配置先:app/Http/Livewire/LiveData.php

<?php
namespace App\Http\Livewire;
use Illuminate\Database\Eloquent\Model;
use \Livewire\Wireable;
use \Livewire\Component;
use Illuminate\Support\Collection;

class ComponentData extends \ArrayObject {
  public bool $dirty = false;
  public function __toString() {
    return var_export($this->getArrayCopy(),true);
  }
  public function offsetSet(mixed $key, mixed $value) {
    parent::offsetSet($key,$value);
    $this->dirty = true;
  }
}

class LiveData extends Model implements Wireable,\IteratorAggregate
{
  protected Collection $components;

  // カレントコンポーネントは LiveRelation の boot で設定される。
  public static Component $current_component;

  // Model のメソッドをオーバーライド
  public function resolveRouteBinding($value, $field = null) {
    $this->components = collect($value)->map(fn($component) => new ComponentData($component));
    return $this;
  }

  // Model のメソッドをオーバーライド
  public function toArray() {
    return $this->components->toArray();
  }

  public function getIterator() {
    return $this->components->keyBy('name');
  }

  public function __construct(array $attributes = []) {
    parent::__construct($attributes);
    $this->components = collect();
  }

  public function __destruct() {
    $this->components
      ->filter(fn($component) => $component->dirty)
      ->each(fn($component) => self::$current_component->emitSet($component['name'],$this));
  }

  public function __invoke(Component $component = null): mixed {
    $component ??= self::$current_component;
    return $this->getComponentData($component->id);
  }

  public function getComponentData(string $needle = null, string $column_key = 'id') {
    $needle ??= self::$current_component->id;
    foreach ($this->components->keyBy($column_key) as $var => $component)
      eval("\$_{$var} = \$component;");
    return ${'_'.$needle} ?? null;
  }

  public function getComponentDataByName(string $name) {
    return $this->getComponentData($name,'name');
  }

  public function __get(mixed $key):mixed {
    return $this->getComponentDataByName($key);
  }

  public function offsetGet(mixed $key):mixed {
    return $this->getComponentDataByName($key) ?? $this->getComponentData($key);
  }

  public function getParent(string $componentId = null) {
    $component = $this->getComponentData($componentId);
    return isset($component['parentId']) ? $this->getComponentData($component['parentId']) : null;
  }

  public function getChildren(string $componentId = null) {
    $component = $this->getComponentData($componentId);
    return collect($component['childIds'])->map(fn($childId) => $this->getComponentData($childId));
  }

  // Wireable 対応
  public function toLivewire() {
    return $this->components;
  }

  // Wireable 対応
  public static function fromLivewire($value) {
    $this->resolveRouteBinding($value);
  }
}

LiveData のポイント
①Modelクラスを継承し、resolveRouteBinding、toArrayメソッド をオーバーライドしてデータベースに関係なく使えるようにしました。
②getComponetメソッド だと「Component が取得できる」と勘違いしてしまうので、getComponentData に変更しました。getParent と getChildren も取得できるものは Component ではありません。
③Wireable に対応し(toLivewire、fromLivewireメソッド追加)、LiveData を emit で送れるようにしました。
④ArrayObject は \Log::dump すると「could not be converted to string」のエラーになってしまうので、ComponentDataクラス を用意しました。
⑤ComponentDataクラス にダーティフラグを持たせて、LiveDataオブジェクト削除時に、自動で他のコンポーネントのプロパティを更新するようにしました。

  1. ライブワイヤーの親コンポーネントを作成します。app/Http/Livewire/Counter.php
<?php
namespace App\Http\Livewire;
class Counter extends \Livewire\Component
{
  use LiveRelation;
  public $count;
  public $count2;
  public function increment() {
    $this->count++;
  }
}

↑「use LiveRelation;」でトレイトを使います。

  1. ライブワイヤーの親コンポーネントのビューを作成します。resources/views/livewire/counter.blade.php
<div style="text-align:center; background-color:#AFA; padding:1em;margin:1em;">
  <livewire:child :count="$count2" bind="count2:count">
  <button type="button" wire:click="increment">+</button>
  <h1>親のCOUNT: {{ $count }}</h1>
  <h1>親のCOUNT2:{{ $count2 }}</h1>
</div>

↑のポイントは2行目の「bind=”count2:count”」です。ここで 親コンポーネントのcount2プロパティ と 子コンポーネントのcountプロパティ を紐づけています。

  1. ライブワイヤーの子コンポーネントを作成します。app/Http/Livewire/Child.php
<?php
namespace App\Http\Livewire;
class Child extends \Livewire\Component
{
  use LiveRelation;
  public $count;
}

↑「use LiveRelation;」でトレイトを使います。

  1. ライブワイヤーの子コンポーネントのビューを作成します。resources/views/livewire/child.blade.php
<div style="padding:1em;background-color:#EFE;">
  <livewire:grand-child :count="$count" bind="count">
  子のプロパティ<input wire:model="count" wire:dirty.class="dirty-flg">
</div>

↑のポイントは2行目の「bind=”count”」です。ここで 子コンポーネントのcountプロパティ と 孫コンポーネントのcountプロパティ を紐づけています。

  1. ライブワイヤーの孫コンポーネントを作成します。app/Http/Livewire/GrandChild.php
<?php
namespace App\Http\Livewire;
class GrandChild extends \Livewire\Component
{
  use LiveRelation;
  public $count;
}

↑「use LiveRelation;」でトレイトを使います。

  1. ライブワイヤーの孫コンポーネントのビューを作成します。resources/views/livewire/grand-child.blade.php
<div style="padding:1em;background-color:#FFF;">
  孫のプロパティ<input wire:model="count" wire:dirty.class="dirty-flg">
</div>
  1. resources/views/index.blade.php を作成します。
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.1/dist/jquery.min.js"></script>
    <livewire:styles />
<style>
.dirty-flg {
  background-color: #F00;
}
</style>
  </head>
  <body>
    <livewire:counter count="1" count2="10" />
    <livewire:counter count="2" count2="20" />
    <button type="button" id="btn">ログ出力</button>
    <button type="button" id="inc">increment</button>
<script>
$('#btn').click(() => {
  for (let i of Livewire.all()) {
    let com = Livewire.find(i.__instance.id)
    console.log(i.__instance.id + "\t" + i.count + "\t" + com.count)
  }
  console.log('');
})

$('#inc').click(() => {
  for (let i of Livewire.all()) {
    if (null == i.bind) {
      i.increment();
    }
  }
})
</script>
    <livewire:scripts />
  </body>
</html>
  1. routes/web.php にルートを定義します。
Route::get('/', fn() => view('index'));
  1. ブラウザでアクセスしてみましょう。

孫コンポーネントのテキストボックスに何か入力すると、「子のプロパティ」と「親のCOUNT2」のプロパティを変更することができます。

以上

Scroll to Top