php LiveWire组件上的方法链接

wpx232ag  于 2023-10-15  发布在  PHP
关注(0)|答案(1)|浏览(103)

我正在尝试创建livewire组件。当我初始化组件时,我想用methodChaining传递一些变量。
举例来说:

class Test extends Component
{
    protected $model;
    protected $fields;
    protected $data;

    public function make(array $fields): static
    {
        $this->fields = $fields;
        return $this;
    }

    public function model($model){
        $this->model = $model;
        if (!$this->query) {
            $this->query($this->model::query());
        }
        return $this;
    }

    public function render()
    {
        $this->ensureValidQuery();
        $this->data = $this->query->get();
        return view($this->view, get_object_vars($this));
    }

}

我想像这样初始化这个组件:

$test = (new Text())->model($this->model)->make([
            __fields__
      ]);

我遇到的问题是组件中的render方法在methodChain之前被调用。所以$model和$fields都是null。
我正在尝试的是Livewire 3吗?如果是这样的话,有人能给我指出正确的方向吗?

jdgnovmf

jdgnovmf1#

可以使用mount方法而不是render方法来执行初始化任务

class Test extends Component
{
    protected $model;
    protected $fields;
    protected $data;

    public function make(array $fields): static
    {
        $this->fields = $fields;
        return $this;
    }

    public function model($model)
    {
        $this->model = $model;
        if (!$this->query) {
            $this->query($this->model::query());
        }
        return $this;
    }

    public function mount()
    {
        // Perform initialization here
        $this->model($this->model)->make($this->fields);
    }

    public function render()
    {
        $this->ensureValidQuery();
        $this->data = $this->query->get();
        return view($this->view, get_object_vars($this));
    }
}

您可以创建并初始化测试组件

$test = (new Test())->model($this->model)->make([
    // Your fields here
]);

相关问题