简体   繁体   中英

How to access declared variable from laravel-livewire component in the app layout

I tried passing a variable from livewire component:

class Index extends Component
{
    public function render()
    {
        return view('livewire.index')->with('type', config('constants.NONAUTH'));
    }
}

and accessing it from layouts.app:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

{{dd($type)}}

@include('includes.head')

...

I get an error that $type is not defined, what is the correct way of doing this?

declare a public variable $type and set this variable inside your mount() function like this:

class Index extends Component
{
    public $type = null;
    
    public function render()
    {
        return view('livewire.index');
    }

    public function mount() 
    {
         $this->type = config('constants.NONAUTH');
    }

}

Edited:

I see, I got you wrong first time,. I read again and came to understand that the thing you want, wont work becuase you are trying to access a variable which is declaring after your app layout. Livewire render its component right after your layout loads. I would recommend you to make your whole app layout using livewire.

Yes there could be various way of declaring something from livewire into your blade. Here is one:

You can fire an event which can be listened by global JS inside your blade. then you can set that value inside your blade component using jquery / vanilla js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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