简体   繁体   English

如何将数据从 Livewire 组件发送到 controller?

[英]How to send data from Livewire component to a controller?

I have a very basic Livewire component.我有一个非常基本的 Livewire 组件。 I know, there is a wire:click , but I simplified it very much, to give you something by hand.我知道,有一个wire:click ,但我非常简化它,手工给你一些东西。 In my real app, there is a calendar component and when you click on an event, it fires the emit() and sends data from the ui to the Livewire component, where it get's modified.在我的真实应用程序中,有一个日历组件,当您单击一个事件时,它会触发emit()并将数据从 ui 发送到 Livewire 组件,并在其中进行修改。

My question is: How can post this data from the Livewire component to the foo.store route?我的问题是:如何将这些数据从 Livewire 组件发布到foo.store路由?

app/Http/Livewire/Foo.php:应用程序/Http/Livewire/Foo.php:

class Foo extends Component
{
    public $foo;

    protected $listeners = [
         'store' => 'store'
    ];

    public function render()
    {
         return view('livewire.foo');
    }

    public function store($data)
    {
         $payload = $this->do_complex_math_on_data($data);
         // ❓ post payload to FooController's store() function - HOW?
    }

    private function do_complex_math_on_data($data)
    {
         return 1+1;
    }
}

resources/views/livewire/foo.blade.php:资源/视图/livewire/foo.blade.php:

<div>
   <button>Click me!</button>
</div>

<script>
    document.addEventListener('livewire:load', function() {
        document.querySelector('button').addEventListener('click' () => {
            Livewire.emit('store', data.coming.from.ui);
        });    
    });
</script>

From your prospect of the controller, as Peppermintology stated, there are two types of controller, one is a standard Laravel controller and the second is a Livewire component controller, from there you have to understand that the livewire controller lifecycle is detached from Laravel. it is working as a waterfall, you can inject data from the Laravel controller to the Livewire component but from Livewire to Laravel standard component you can't, though you can pass data between the livewire ecosystem like from parent component to child or vice-versa From your prospect of the controller, as Peppermintology stated, there are two types of controller, one is a standard Laravel controller and the second is a Livewire component controller, from there you have to understand that the livewire controller lifecycle is detached from Laravel. it作为瀑布工作,您可以将数据从 Laravel controller 注入到 Livewire 组件,但是从 Livewire 到 Laravel 标准组件您不能,尽管您可以在 livewire 生态系统之间传递数据,例如从父组件到子组件,反之亦然

Like below像下面一样

$this->emitUp('postAdded');

or或者

<button wire:click="$emitUp('postAdded')">

you can read more about nesting components in livewire Nesting component , and also about event Events您可以在 livewire嵌套组件中阅读有关嵌套组件的更多信息,以及有关事件事件的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM