Using Vue.js to showcase real-time Pusher data in Laravel 5.4

I am currently working on developing a real-time chat application using vue.js, Pusher, and Laravel. I have successfully managed to receive information from Pusher, as I can view the JSON data in the console with the correct details. However, I am facing a challenge in merging the existing messages fetched from the database using fetchMessages with the new Pusher messages received in real-time, and displaying them together.

Message Display

<div id="app">
    <article v-for="message in messages">
        <h3> User ID: @{{ message.user_id }}</h3>
        <p> @{{message.body}} </p>
    </article>
</div>

Vue Configuration

new Vue({
el: '#app',

data: {
    messages: []
},

ready: function() {
    this.fetchMessages();

    var pusher = new Pusher('key_here', {
        encrypted: true
    });

    var channel = pusher.subscribe('cars');
    channel.bind('App\\Events\\UserHasNewMessage', function(data) {
        console.log(data);
        /*
             I can output my pusher data to the console just fine. 
             But how can I append this data to the existing messages?
        */
    });
},

methods: {
    fetchMessages: function() {
        this.$http.get('/api/messages', function(messages){
            this.$set('messages', messages);
        });
    }
}
})

Answer №1

You have three options for achieving this:

In ES5:

  1. Append .bind(this) at the end of the function to access this within the function

    channel.bind('App\\Events\\UserHasNewMessage', function(data) {
         this.messages.push(data);
    }.bind(this));
    
  2. Set this equal to a variable and utilize that variable in the function

    var that = this;
    channel.bind('App\\Events\\UserHasNewMessage', function(data) {
         that.messages.push(data);
    }.bind(this));
    

In ES6:

  1. Utilize the fat arrow to enable using this inside the function

    channel.bind('App\\Events\\UserHasNewMessage', (data) => {
         this.messages.push(data);
    });
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clicking will open the link in both a new tab and the current tab

I'm looking to enable ng click functionality to work in both new tabs and the current tab. The URL is dynamically generated based on a certain condition. Here is the HTML: <a ng-href="{{myPathVariable }} " ng-click=" GoToThemes()" class="shift-l ...

Retrieving a subset of an array column in Sequelize: A comprehensive guide

I am currently working with a table that has an array column named tokens When querying this table using npm sequelize, I sometimes encounter an issue where the tokens column contains up to 20k elements, even though I only need 10 elements from it. In st ...

Using jQuery ajax in PHP, the ability to remove retrieved information from a different page is a

I'm currently working on a jQuery AJAX PHP application that allows for adding, deleting, and displaying records using switch case statements to streamline the code. Everything seems to be functioning correctly with inserting and displaying records, bu ...

Exploring the Wonder of MVC with Ajax Calls Handling Multiple Parameters

I've been struggling to send 2 parameters from the View to the controller using an ajax call. Everything was working fine when I had only one parameter, but as soon as I added another, the function stopped working. Below is the Javascript code with a ...

Create a curve using two distinct colors in JavaScript

I am currently experimenting with a canvas and I have a specific challenge in mind. My goal is to draw an arc using two different colors, where the first half of the arc will be green and the second half red. Check out the code snippet below: // CANVAS co ...

I find myself a little mixed up with this syntax in JavaScript: `arr.indexOf(searchElement[, fromIndex])`

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // ...

Creating a Vue JS project that utilizes both HTTP and HTTPS URLs for improved security

I'm currently utilizing Vue JS with the webpack template and dev mode. I have a question regarding how to configure my server to allow for both HTTPS and HTTP protocols simultaneously. I understand that enabling HTTPS can be done by simply adding "ht ...

Need to obtain the stack trace from the catch block in a request-p

Currently, I am utilizing the 'request-promise' library in my node-js application for making API calls. However, I am facing challenges in obtaining the correct call stack from the 'catch' function. Upon experimenting with it, I discove ...

Disabling the visibility of elements through a transparent sticky-top menu

I'm having an issue with my website design. I have a gradient background and a sticky-top menu on the site. The problem is that when I scroll down, the content appears through the menu, which is not ideal. I don't want to apply the same gradient ...

How to automatically set the radio button as "checked" with Javascript upon loading the page

With the dark mode switch javascript from Bootstrap 5 (https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript), I am attempting to ensure that a radio button is set to "checked" when the page loads, as well as when the color mode is changed. ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...

One effective way to redirect after a PUT request and display a one-time message

Here's what I'm aiming for in terms of desired behaviour: A user navigates to a password change web page. The user completes the form and it is sent via PUT request to our REST server. Upon successful completion, the user is redirected to their ...

Transitioning the image from one point to another

I am currently working on a unique single-page website and I have been experimenting with creating dynamic background animations that change as the user scrolls. Imagine my website is divided into four different sections, each with its own distinct backgro ...

Is there a way to verify whether a user is currently logged in? (Using everyauth in node.js)

Previously, I relied on client-side auth for my application. Recently, I integrated server-side everyauth and it's functioning well. However, I'm unsure how to perform a function similar to FB.getLoginStatus (which I used in the client-side) when ...

Utilizing jQuery to extract the value of a selected list item on click

I have been working on creating a list of items from JSON data and am facing an issue with retrieving the 'data-value' attribute of the clicked item. Here is my current code: const target = $('#list'); target.empty(); for (let i = 0 ...

Enhance your web form with an auto-suggest textbox that allows for multiple selections,

Looking for assistance in implementing an auto complete text box with the ability to select multiple options using Dojo. Any experts out there who can offer their guidance? ...

Firefox not clearing Highcharts points properly

I am currently utilizing highcharts to generate dynamic charts when hovering over a table row. My goal is to clear and hide the chart once the mouse moves away from the row. While this functionality works smoothly in Chrome, I am encountering a strange is ...

Best Practices for Managing Asynchronous Updates in Angular Controllers

Let me explain my current setup -- I have a controller that utilizes a service to perform some tasks and then fetches data asynchronously. Right now, the data is returned after a timeout, but ideally it would involve more complex operations: This is how m ...

Tips for implementing a distinct texture on child elements through traversal techniques

My current dilemma involves working with an object that I've loaded using THREE.ObjectLoader(). This object consists of various elements, resembling a simple box made up of panels and sticks. My goal is to assign different textures to specific child ...