【问题标题】:Transform piece of laravel livewire code into Facade or trait将一段 laravel livewire 代码转换为 Facade 或 trait
【发布时间】:2021-10-01 09:48:31
【问题描述】:

我正在尝试将以下代码转换为外观。 但我不知道如何在门面调用$this。我想在不使用$this 或将其作为参数传递的情况下执行此操作。我可以以某种方式依赖注入吗?

以下代码位于 livewire 组件中,该组件将调度事件以通过 JS 侦听器显示 toast。

//turn this
$this->dispatchBrowserEvent('showToast', ['name'=>'success','title' => 'Updated','message'=>'Your data is saved']);
//into this
        
 $toast::success('Updated','Your data is saved');

如何简化这段代码?

【问题讨论】:

    标签: laravel traits laravel-livewire laravel-facade


    【解决方案1】:

    我通常会创建一个 trait Toast。

    trait Toast 
    {
        public function successAlert(string $title, string $message)
        {
             $this->dispatchBrowserEvent('showToast', [
                  'name' => 'success',
                  'title' => $title,
                  'message' => $message,
             ])
        }
    }
    

    然后在我使用的 livewire 组件上:

    class MyComponent extends Component 
    {
         use Toast;
    
         public function save()
         {
              // save
              $this->successAlert('Updated','Your data is saved'); 
         }
    }
    

    我想不出一种简单的方式来实现外观,因为您需要访问 livewire 组件的内部功能来调度浏览器事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多