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

Using TypeScript to specify data types in the Vue data object

I am currently utilizing Vue.js with Typescript in a webpack project. Following the guidelines provided in the Recommended Configuration in my tsconfig.json, I have set: "strict": true, Within one of my components, I have: declare interface P ...

AngularJS - Use promise instead of returning a data object

I am currently working on a project using AngularJS. Within my service.js file, I am attempting to retrieve some values. However, instead of receiving the actual data, I am getting back a promise object with some $$variables along with the desired data. ...

The jQuery autocomplete feature seems to be malfunctioning as no suggestions are showing up when

I am currently generating input text using $.each: $.each(results, function (key, value) { if (typeof value.baseOrSchedStartList[i] != 'undefined') { html += "<td><input type='te ...

Locating the source of the function call within a file in Node.js

Is it possible to determine the location of a file if a method from a module is called within that file? For example: // my-module.js module.exports = { method: function () { // I would like to know the path to my-app.js here } } // my-other-mod ...

Having trouble with ESLint in VSCode? The ESLint extension seems to be ignoring linting rules after starting a new project within VSCode

I recently started using the ESLint extension in my VSCode editor for my React project. After creating the starter files, I ran the following command in my terminal: eslint --init This allowed me to choose the AirBnb style guide with React, which generat ...

Accessing JavaScript cookie within .htaccess file to establish redirection parameters according to cookie content

Is there a way to modify the rules within my .htaccess file so that it can properly read a user-side cookie and redirect based on its content? The scenario is this: I have a cookie called userstate which contains an abbreviation of US states, such as AL ( ...

Executing method before uploading in Vue.js + Element-UI: Pre-upload function integration

Why isn't the handleBeforeUpload function being called during file upload? Am I missing something? I need to restrict users to selecting only CSV files. I am using Vue3 with Composition API and Element-plus UI. Though there is an example on the Elem ...

Discovering whether input field is currently in focus using jQuery

Does anyone know how to determine if an input tag in HTML has focus using jQuery? The keydown event will function for forms when input, image, etc. tags have focus. However, it will not work if the focus is on the form itself but not on any specific tags ...

The performance of the React create app proxy agent in the package.json file seems to be sluggish,

In our react application (created as create-react-app), we have a proxy defined in the `package.json`. This proxy is used between the front-end (webpack) and back-end (express) during development, as outlined here. The section of the `package.json` where t ...

empty responseText from GET request using AJAX

I've been working on a chatbox using AJAX and I've encountered an issue where my xhttp.responseText is coming back empty. In firebug, I can see that the GET request is being sent and the correct text is being returned, but for some reason it&apos ...

Tips for sending information to a modal window

I need to transfer the userName from a selected user in a list of userNames that a logged-in user clicks on to a twitter bootstrap modal. I am working with grails and angularjs, where data is populated using angularjs. Set-Up The view page in my grails a ...

IE displaying "slow script" alert due to Knockout malfunction

Within my grid of observables and computed observables, the first row serves as a multiplier for all subsequent rows. Users can modify this percentage rate and Knockout automatically updates all relevant values accordingly. Additionally, I require a textbo ...

Unable to access object key data from JSON-SERVER

I am currently attempting to send a GET request to json-server in order to retrieve data from a nested object. However, the response I am receiving is empty instead of containing the desired data key. After thoroughly reviewing the documentation, I could ...

Adjust the color of the navbar only after a user scrolls, with a slight delay rather than

My code changes the navbar colors when I scroll (200ms). However, I would like the changes to occur when I am slightly above the next section, not immediately. In other words, what adjustments should I make to change the color in the next section and not ...

Error: The parent container element cannot be edited until the child element has been properly closed

I received a Script Error stating that I am unable to modify the parent container element before the child element is closed. In response, I clicked Yes but my web page isn't being displayed. In the code for my Product page, I start with: http://past ...

What is the significance of the term "Object object"?

I am new to javascript and encountering an issue. When I use alert in my script, the output data is shown as [Object object]. The function below is called when the button (onClick) is clicked. There are [Object object] elements in the array. The last line ...

Optimal approach for managing numerous modals containing map data in Next.js

Hey there, I'm facing an issue while trying to utilize map data in conjunction with modals. Although I have set the state for all modals, when I use an array object within the map data, the modals end up showing duplicated. To provide clarity, let me ...

Recording audio using Cordova and Javascript

Recently, I've been dabbling in creating a new app using Cordova, VueJs, and Onsen UI for VueJs. One of the main features I want to implement is the ability to use the microphone on Android or iOS devices to record audio and then send it to the Google ...

Utilize jQuery and PHP to populate an HTML Select Field with data retrieved from a MySQL Database in JSON format

I am exploring how to Transfer Database Data into an HTML Dropdown Selection Field using jQuery. I came across a useful example that seems promising. Although I am new to jQuery and JavaScript, I am eager to learn. My goal is similar to the approach descr ...

New replacement for routerState.parent feature that has been deprecated in angular2

During my work with Angular 2 rc5, I encountered the following code snippet. this.router.routerState.parent(this.route).params.forEach((params: Params) => { url = params['url']; id = +params['id']; }); I had to resort to th ...