微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

使用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]

解决方法

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

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

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

为了在函数中传递参数(字符串),请确保使用单 '' 引号,注意双引号 ""。喜欢:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。