繁体   English   中英

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

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

我尝试从 livewire 组件传递一个变量:

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

并从 layouts.app 访问它:

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

{{dd($type)}}

@include('includes.head')

...

我收到$type未定义的错误,这样做的正确方法是什么?

声明一个公共变量 $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');
    }

}

编辑:

我明白了,我第一次误会你,。 我再次阅读并了解到您想要的东西不会起作用,因为您正在尝试访问在您的应用程序布局之后声明的变量。 Livewire 在布局加载后立即渲染其组件。 我建议您使用 livewire 制作整个应用程序布局。

是的,可以通过多种方式将 livewire 中的某些内容声明到刀片中。 这是一个:

您可以触发一个事件,该事件可以被刀片内的全局 JS 监听。 然后您可以使用 jquery / vanilla js 在刀片组件中设置该值。

暂无
暂无

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

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