首页 > 解决方案 > Livewire:无法调用组件方法。在组件上找不到公共方法 [childMethodName]:[父]

问题描述

使用 Laravel Livewire,我有一个父母和一个(重复的)孩子。child Blade 有一个 call to 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()
        ]);
    }
}

父母statements-table.blade

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

子组件:

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');
    }
}

孩子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>

为什么我会得到

Livewire\Exceptions\MethodNotFoundException
Unable to call component method. Public method [childMethod] not found on component: [statements-table]

标签: phplaravellaravel-livewire

解决方案


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

确保孩子的视图有一个根元素,如Livewire Docs中所示。


推荐阅读