【Laravel實戰】10分鐘搞懂Livewire的Traits運用

【Laravel實戰】10分鐘搞懂Livewire的Traits運用

PHP Traits 是用來在多個 Livewire 組件之間重用程式碼非常好用的方式

例如,你可能想要有多個 "data table" 組件在你的應用裡頭,它們都共同使用相同的邏輯來進行排序。與其複製以下的這些排序邏輯到每一個組件裡頭,你應該試試其他更好的做法:

//app/Http/Livewire/ShowPosts.php

class ShowPosts extends Component
{
    public $sortBy = '';
    public $sortDirection = 'asc';

    public function sortBy($field)
    {
        $this->sortDirection = $this->sortBy === $field
            ? $this->reverseSort()
            : 'asc';

        $this->sortBy = $field;
    }

    public function reverseSort()
    {
        return $this->sortDirection === 'asc'
            ? 'desc'
            : 'asc';
    }

    ...
}

你可以把這些程式碼轉到一個可重複利用的 trait ,取名為 WithSorting :

//app/Http/Livewire/ShowPosts.php

use app\Http\Traits\WithSorting

class ShowPosts extends Component
{
    use WithSorting;

    ...
}
//app/Http/Traits/WithSorting.php

trait WithSorting
{
    public $sortBy = '';
    public $sortDirection = 'asc';

    public function sortBy($field)
    {
        $this->sortDirection = $this->sortBy === $field
            ? $this->reverseSort();
            : 'asc';

        $this->sortBy = $field;
    }

    public function reverseSort()
    {
        return $this->sortDirection === 'asc'
            ? 'desc'
            : 'asc';
    }
}

除此之外,假如你想要在你的 trait 裡頭去使用 Livewire 的 hook 同時也想要在組件裡頭使用 hook。沒問題, Livewire 提供了一個語法來允許你這麼做

//app/Http/Traits/WithSorting.php

trait WithSorting
{
    ...

    public function mountWithSorting()
    {
        //
    }

    public function updatingWithSorting($name, $value)
    {
        //
    }

    public function updatedWithSorting($name, $value)
    {
        //
    }

    public function hydrateWithSorting()
    {
        //
    }

    public function dehydrateWithSorting()
    {
        //
    }

    public function renderingWithSorting()
    {
        //
    }

    public function renderedWithSorting($view)
    {
        //
    }
}

分享這篇文章:

關聯文章:

訂閱電子報,索取 Laravel 學習手冊

價值超過 3000 元,包含常用 Laravel 語法與指令!

Laravel 百萬年薪特訓營

從最基礎的 PHP 語法開始,包含所有你該知道的網頁基礎知識,連同 Laravel 從零開始一直到實戰,最後還將告訴你如何找好工作,讓你及早擁有百萬年薪