如何在Laravel和Vue JS中使用Pusher创建实时聊天?

时间:2019-07-16 17:34:02

标签: laravel pusher laravel-echo

我是laravel的新手,我已经与laravel和vue js以及pusher进行了实时聊天。我想用代码一切都很好,但是聊天不能实时进行。我需要帮助,只是想知道我的代码在哪里错了。下面是我的代码。

<?php

namespace App\Events;

use App\Message;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Message $message)
    {
        //
         $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
         return new PrivateChannel('messages.' . $this->message->to);
    }

    public function broadcastWith()
    {
        $this->message->load('fromContact');

        return ["message" => $this->message];
    }

    public function broadcastAs()
    {
        return 'message';
    }
}
<template>
  <div class="composer">
    <textarea v-model="message" @keydown.enter="send" placeholder="Message..."></textarea>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: ""
    };
  },
  methods: {
    send(e) {
      e.preventDefault();

      if (this.message == "") {
        return;
      }

      this.$emit("send", this.message);
      this.message = "";
    }
  }
};
</script>

<style>
.composer textarea {
  width: 96%;
  margin: 10px;
  resize: none;
  border-radius: 3px;
  border: 1px solid lightgray;
  padding: 6px;
}
</style>

这是我尝试过的。一切正常。我只需要刷新页面,但是我希望它不刷新页面。我要实时。请让我知道我的代码在哪里错误。我不知道,我遵循了在线教程并且运行正常,但是我不知道我的代码的问题在哪里。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您尚未订阅频道,也没有收听代码中的事件。