Laravel websockets + Pusher + Vue.js

Video tutorial


Tutorial part 1

Tutorial Part 1

Tutorial part 2

Vuej.js

Install vue

npm install
npm install --save vue

routes/web.php

Route::get('/vue-message', function () {
    return view('message');
});

resources/views/message.blade.php

<!DOCTYPE html>
<html >
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>
        <link rel="stylesheet" href="https://getbootstrap.com/2.3.2/assets/css/bootstrap.css">

        <style type="text/css">
          html,body {height: 100%;}
          #wrap {
            min-height: 100%;
            height: auto !important;
            height: 100%;
            margin: 0 auto -60px;
          }
          #push, #footer { height: 60px; }
          #footer { background-color: #f5f5f5; }
          .container { width: auto; max-width: 680px; }
          .container .credit { margin: 20px 0; }
        </style>
    </head>
    <body>
        <div id="app">
          <div id="wrap">
            <div class="container">
              <div class="page-header">
                <h1>Laravel + Websockets + Vue.js</h1>
              </div>
              <h3> Message </h3>
              <!-- component vue -->
              <message-component></message-component>
            </div>
          </div>
        </div>
        <!-- importar component vue -->
        <script src="{{ asset('js/app.js') }}" ></script>
    </body>
</html>

Script pusher

<script src="https://js.pusher.com/5.1/pusher.min.js"></script>

resources/js/app.js

require('./bootstrap');

import Vue from 'vue';

Vue.component('message-component',require('./components/MessageComponent.vue').default);

const app = new Vue({
    el: '#app',
});

resources/js/components/MessageComponent.vue

<template>
  <div>
    <p v-for="msg in message">
      <b>{{msg.user}} : </b> {{msg.message}}
    </p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: [],
    }
  },
  mounted(){
   console.log("Mounted app message");
   // Enable pusher logging - don't include this in production
    Pusher.logToConsole = true;
    const APP_KEY = 'XXXXXXXXXXXXXXXXXXXX'
    var pusher = new Pusher(APP_KEY, {
      cluster: 'us2',
      forceTLS: true
    });
    const self = this
    var channel = pusher.subscribe('channel-tutofox');
    channel.bind('event-pusher', function(data) {
      // app.messages.push(JSON.stringify(data));
      const message = self.message
      message.push(data.data)
    }); 
  }
}
</script>

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *