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

问题描述 投票:0回答:4

使用 Laravel Livewire,我有一个父母和一个(重复的)孩子。子刀片通过

childMethod()
调用
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]
php laravel laravel-livewire
4个回答
6
投票

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

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


0
投票

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

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

<button wire:click="$emitSelf('childMethod')">

0
投票

要在函数中传递参数(字符串),请确保使用单引号

''
,注意双引号
""
。喜欢:

wire:click="activeTab('product')"

0
投票

如果您使用的是 livewire 版本 3,则“emit”方法已重命名为“dispatch”。 (同样,emitTo()和emitSelf()现在是dispatchTo()和dispatchSelf())。

查看文档:https://livewire.laravel.com/docs/upgrading#events

© www.soinside.com 2019 - 2024. All rights reserved.