Livewire:无法调用组件方法。在组件:[parent] 上找不到公共方法 [childMethodName]

Pau*_*ulH 5 php laravel laravel-livewire

使用 Laravel Livewire,我有一个父母和一个(重复的)孩子。子刀片有一个呼叫childMethod()through wire:click="childMethod()"。

问题是当parent->childMethod()我想child->childMethod()被呼叫时却被呼叫了。

父组件

class StatementsTable extends Component // parent
{
    public function render()
    {
        return view('livewire.statements-table', [
            'statements' => Statement::limit(10)->get()
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

家长statements-table.blade

<table class="table">
    @foreach($statements as $statement)
        @livewire('statement-line', ['statement' => $statement], key($statement->id))
    @endforeach
</table>
Run Code Online (Sandbox Code Playgroud)

子组件:

class StatementLine extends Component
{
    public $statement;
    public $calls = 0;

    public function childMethod()
    {
        $this->calls += 1;
    }

    public function mount($statement): void
    {
        $this->statement = $statement;
    }

    public function render()
    {
        return view('livewire.statement-line');
    }
}
Run Code Online (Sandbox Code Playgroud)

孩子statement-line.blade

{{-- dd(get_defined_vars()) --}}
<tr>
    <td>{{$statement->name}}</td>
    <td>{{$statement->date}}</td>
    <td>{{$calls}}</td>
    <td><button wire:click="childMethod">Plus</button></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

为什么我得到

Livewire\Exceptions\MethodNotFoundException
Unable to call component method. Public method [childMethod] not found on component: [statements-table]
Run Code Online (Sandbox Code Playgroud)

小智 5

有同样的问题。解决方案是:

确保子视图有一个根元素,如Livewire 文档中所示。


Sid*_*rth 0

您可以在 livewire 中确定回调的范围,查看此处提供的文档https://laravel-livewire.com/docs/2.x/events#scoping-events

对于你的情况,你应该像这样自我调整

<button wire:click="$emitSelf('childMethod')">
Run Code Online (Sandbox Code Playgroud)