Livewire 3: How to Make Cross-Component Calls?

$ 5
chris
chris

Comment Component

Path: app/Livewire/comments/index.php

<?php
 
namespace App\Livewire;

use Livewire\Component;
 
class Comment extends Component
{
    public string $rawData;
}

Path: resources/views/livewire/comments/index.blade.php

<input type="text" placeholder="Please complete the information."  name="rawData" >
<div id="showActionData">{{!! $data !!}}</div>
<button click="getMixData(rawData)">Click to get processed data</button>

Helpp Component

Path: app/Livewire/data.php

<?php
 
namespace App\Livewire;

use Livewire\Component;
 
class Helpp extends Component
{
    public function getMixData($rawData)
    {
        // Action
        return $data; // html  tag data
    }
}

I aim to implement a feature where, upon clicking the button in the Comment component, the input data is transferred to the getMixData method of the Helpp component for processing. Subsequently, the processed data will be displayed within the Comment component itself.

Solved
  • test1

    test1

    namespace App\Livewire;
    
    use App\Models\Vehicle;
    use Livewire\Component;
    
    class Comment extends Component
    {
        public string $rawData;
        public string $data;
    
        protected $listeners = [
            'get-processed-data' => 'getProcessedData',
        ];
    
        public function getMixData($rawData)
        {
            $this->emitTo('helpp','get-mix-data', $this->rawData);
        }
    
        public function getProcessedData($processedData)
        {
            $this->data = $processedData;
        }
    
    }
    
    namespace App\Livewire;
    
    use Livewire\Component;
    
    class Helpp extends Component
    {
        protected $listeners = [
            'get-mix-data' => 'getMixData',
        ];
        public function getMixData($rawData)
        {
            $processedData = $rawData;
            $this->emitTo('component','get-processed-data', $processedData);
        }
    }
    

    Please call me Lei Feng.

  • Liu
  • Ethan

    Ethan

    Just emit an event and listen for the event in the other component.

    Dispatching events

    You can also dispatch this event from your frontend directly.

    Dispatching Livewire events from Alpine

This question has been resolved and no bounty will be distributed.