简体   繁体   English

如何从应用布局中的 laravel-livewire 组件访问声明的变量

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

I tried passing a variable from livewire component:我尝试从 livewire 组件传递一个变量:

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

and accessing it from layouts.app:并从 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?我收到$type未定义的错误,这样做的正确方法是什么?

declare a public variable $type and set this variable inside your mount() function like this:声明一个公共变量 $type 并在你的 mount() function 中设置这个变量,如下所示:

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. Livewire 在布局加载后立即渲染其组件。 I would recommend you to make your whole app layout using livewire.我建议您使用 livewire 制作整个应用程序布局。

Yes there could be various way of declaring something from livewire into your blade.是的,可以通过多种方式将 livewire 中的某些内容声明到刀片中。 Here is one:这是一个:

You can fire an event which can be listened by global JS inside your blade.您可以触发一个事件,该事件可以被刀片内的全局 JS 监听。 then you can set that value inside your blade component using jquery / vanilla js.然后您可以使用 jquery / vanilla js 在刀片组件中设置该值。

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

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