【问题标题】:Livewire: Unable to call component method. Public method [childMethodName] not found on component: [parent]Livewire:无法调用组件方法。在组件上找不到公共方法 [childMethodName]:[父]
【发布时间】:2021-01-29 22:10:16
【问题描述】:

使用 Laravel Livewire,我有一个父母和一个(重复的)孩子。子刀片通过wire:click="childMethod()" 调用了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]

【问题讨论】:

  • 代码太多,无法回答
  • @PaulH 我也遇到了这个问题。你找到解决办法了吗?

标签: php laravel laravel-livewire


【解决方案1】:

遇到了同样的问题。解决方案是:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      对于您的情况,您应该像这样选择自我

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

      【讨论】:

        猜你喜欢
        • 2019-04-14
        • 1970-01-01
        • 2018-02-22
        • 1970-01-01
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        • 2018-06-24
        • 1970-01-01
        相关资源
        最近更新 更多