变量中的 Livewire 实例将自身设置为 null

Livewire instance in variable sets itself null

在我的 laravel livewire 组件中,我有这段代码。

private $wireAlertService;

public function mount() {
    $this->supervisors = User::getSupervisors();

    $this->wireAlertService = new LivewireAlertService();

    // dd($this->wireAlertService);
}

注释掉的 dd() 根据需要转储 LivewireAlertService 的实例。

然而,在其他方法中,触发按钮的 wire:click,变量 $wireAlertService 为空。

public function approveMany($attrs) {

    // code

    dd($this->wireAlertService, (new LivewireAlertService()));
    // $this->wireAlertService->success($this);
    // (new LivewireAlertService())->success($this);
}

在方法中 approveMany() dd() 转储这个

null
App\Services\LivewireAlertService {#2760}

因此 $this->wireAlertService->success($this); 不起作用(所需的) 虽然 (new LivewireAlertService())->success($this); 有效,但我不太喜欢它。

如 Livewire introduction 中所述,protectedprivate 属性不会持续存在。因此,在您的安装完成后,属性 将被重置。

如果你希望它持久化,你需要立即定义它,但是使用 class 实例化或使 属性 public 是不可能的。

根据服务内容,您可以inject it into each method, much like you would with the Request