Livewire Laravel 找不到回声

Livewire Laravel Echo cannot be found

我在 livewire 组件中有一个轮询事件,在组件 blade Laravel Echo cannot be found 中抛出。我按照文档安装了 Laravel echo 并在 bootstrap.js

中取消注释

但是我的布局使用的是 jquery 因此我在主布局的 app.js 脚本中删除了 defer。我的格式是这样的,这是我布局的头部部分。

@livewireStyles
@livewireScripts
  
<script src="{{ mix('js/app.js') }}" ></script>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.8.2/dist/alpine.min.js" defer></script>

bootstrap.js

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

import Echo from 'laravel-echo';

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: true
});

我阅读了 livewire 文档,它说我的 window.Echo object 必须在全球范围内可用。我不确定我是否做对了。

我的组件

class PaddleConfirm extends Component
{
    public $newPaymentNotification = false;

    protected $listeners = ['echo:orders,UserPayment' => 'notifyNewOrder'];

    public function notifyNewOrder()
    {
        // $this->newPaymentNotification = true;
        
        Log::info("new payment method");
    }


    public function render()
    {
          return view('livewire.paddle-confirm');
    }
}

我的事件被触发但是组件没有监听这个,也许是因为 Echo not found warning。非常感谢任何帮助。

使用 Livewire:v2.0 使用 Laravel :v8.40

我找到了类似的 question 但它没有解决我的问题

Livewire 脚本应该在 body 标签的末尾,而不是在头部,因为这是使它能够以正确的顺序启动的原因。

先尝试移动它,看看会发生什么。

还建议将 app.js 脚本也放在 body 标记的末尾,或者将 defer 添加回 app.js 脚本,因为 defer 不会阻止它在您的布局中使用, 它只是控制 JS 脚本的启动顺序。


<head>
    <!-- other head stuff here -->

    @livewireStyles

    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.8.2/dist/alpine.min.js" defer></script>
</head>

<body>
    <!-- body stuff here -->
    
    @livewireScripts
    <script src="{{ mix('js/app.js') }}" ></script>
</body>

该解决方案由 joshhanley 在 Github Discussion 上引用并提供。归功于他