【发布时间】:2020-07-19 23:56:02
【问题描述】:
我正在使用带有 Vue.js 和 Laravel-echo 的 Laravel 7。
我已经在我的应用程序中使用 npm install --save laravel-echo pusher-js 安装了 Laravel Echo 库,并且还根据 laravel 提供的文档在 resources/assets/js/bootstrap.js 文件中包含了以下代码,并且我在 app.js 和 @ 中有 require('./bootstrap'); app.blade.php 中的 987654325@。
但我收到以下错误:
bootstrap.js:
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
});
show.blade.php
<script>
const app = new Vue({
el: '#app',
data: {
comments: {},
commentBox: '',
post: {!! $post->toJson() !!},
user: {!! Auth::check() ? Auth::user()->toJson() : null !!}
},
created: function() {
this.listen();
},
methods: {
listen: function() {
Echo.channel('post.'+this.post.id)
.listen('NewComment', (comment) => {
// this.comments.unshift(comment);
console.log('yessss');
})
}
}
});
</script>
事件:NewComment.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast; //for queueing
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; //for no queueing
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Comment;
class NewComment implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $comment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Comment $comment)
{
$this->comment = $comment;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('post.'.$this->comment->post->id);
}
}
.env:
PUSHER_APP_ID=xxxxxx
PUSHER_APP_KEY=xxxxxxxxxxxxxxxxxx
PUSHER_APP_SECRET=xxxxxxxxxxxxx
PUSHER_APP_CLUSTER=xxx
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
我尝试删除 forceTLS: true 但仍然无法正常工作。我尝试添加 window.Echo,但收到其他错误:“TypeError: Cannot read property 'channel' of undefined”
此错误的任何解决方案?!提前感谢您的帮助!
【问题讨论】:
-
你运行
npm run watch吗? -
@kerbholz 是肯定的!
-
你试过
window.Echo.channel吗? -
是的,我收到:TypeError: Cannot read property 'channel' of undefined @Purgatory
标签: laravel vue.js websocket laravel-echo pusher-js