Transferring data from SocketIO to Vue.js

Is there a way to effectively transfer data results received from socketIO to the Vue instance? Below is my current code implementation:

let socket = io();
let users;

socket.on('user-connected', (data) => {
    users = data.count;
});
socket.on('user-disconnected', (data) => {
    console.log(data.count);
});

new Vue({
    el: '#playersCounter',
    data: {
        playerCounter: users
    }
});

HTML:

<div class="d-flex justify-content-start" id="playersCounter">
    <p class="onlinePlayersCounter">Online: {{playerCounter}}</p>
</div>

Currently, I am not receiving any errors but the data is not being displayed as expected.

Answer №1

Here is a solution:

let connection = new WebSocket('ws://example.com/socket');

new Vue({
    el: '#onlineUsersCounter',
    data: {
        usersCount: totalUsers
    },
    created: function() {
        connection.onopen = function() {
            console.log('Connection opened');
        };

        connection.onmessage = function(event) {
            let response = JSON.parse(event.data);
            this.usersCount = response.count;
            console.log(response.count);
        };

        connection.onerror = function(error) {
            console.error('WebSocket Error: ' + error);
        };
  },
});

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

What is the best approach to send data to the parent when closing $mdDialog?

When I open a Dialog Window, it has its own controller. Is there a way for me to modify data in the differentController that belongs to the Dialog Window and then send the modified data back to the parent controller when the dialog is being removed? fun ...

What is the most effective method for integrating additional CSS/JS libraries into a GitHub repository?

I would like to integrate FontAwesome, Bulma, jquery, and jquery-ui into one of my Github repositories for the front-end section. Currently, I am including the JS files or CSS files from these projects in my own JS/CSS folders, but I believe there might ...

Using AngularJS, trigger an httpget request when the value in a textbox is changed

I am currently working on a web service that returns a json file when called with an entry ID parameter. I have successfully created an Angular method to retrieve the data from this service. However, I am facing difficulty in recalling the service when the ...

Animating transitions in a Vuetify data table

I am in the process of animating the data on a Vuetify data table. My objective is to make the current data slide out to the right when Next is clicked, and then have the new data slide in from the left. The current result I am getting can be viewed here: ...

The provider for authentication, which is linked to the AuthenticationService and subsequently to the loginControl, is currently unidentified

Attempting to implement an authentication service in my application, I encountered an error when trying to call it within my controller: !JavaScript ERROR: [$injector:unpr] Unknown provider: AuthenticationServiceProvider <- AuthenticationService <- ...

How can you center the body of a webpage while using the zoom in and zoom out features in HTML5?

What is the best way to maintain body alignment while zooming in and out on a web page? <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> body { font-family: 'Merriweather Sans&apos ...

Unearthing the worth of the closest button that was clicked

I am currently working on a profile management feature where I need to add students to the teacher's database. To achieve this, I am using jQuery and AJAX. However, I am encountering an issue where clicking the "add" button for each student listed on ...

Is the state of the React.js component empty?

HTML: <!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>React Tutorial</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> ...

Retrieving the passed argument variable and utilizing it as a key in a map

I've been working on a JavaScript project recently and I've encountered a situation where I believe my code could be significantly reduced - up to 50% - if I could access the passed arguments to a function and use them as keys. Since I'm sti ...

Experiencing difficulties with $watch in my Angular controller

Having trouble getting a $watch function to work properly while testing a controller. In this scenario, the goal is to display ctrl.value in either ARI format or AEP format, but the underlying $scope.model is always kept in the ARI format. When ctrl.value ...

Encountered issue post deploying Vue application on portal.Azure

Upon creating my Vue-Vite app, I proceeded to establish a repository on dev.azure for the Web App. Following this, I deployed it on portal.azure.com. Despite resolving a few errors, I am now faced with unfamiliar issues: Main.css:1 Failed to load module ...

JavaScript: Targeting elements by their tag name within a designated container

When working with PHP, it is possible to use the getElementsByTagName method on any DOM object. However, this concept does not seem to exist in JavaScript. For example, if we have a specific node stored in the variable detailsNode, attempting to use detai ...

How to extract a variable from a mongoose find method in a Node.js application

Within my Node.js program, I utilize my Mongoose database to query for a specific value in a collection, of which there is only one value present. var myValueX; myCollection.find(function(err, post) { if (err) { console.log('Error ...

The NextAuth file imported with the EmailProvider is currently not being utilized

Having an issue with implementing nextauth for authentication. I have imported EmailProvider from nextauth/providers but when I try to use it in the Nextauth providers object, it does not recognize the EmailProvider that I've imported. Here is the co ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

Can Google Charts be integrated with $refs in VueJS?

I'm currently working on implementing a timeline chart with Google Charts. The chart is displayed within its own component, which I later invoke from a higher-level parent component. However, I've run into an issue where the drawChart function re ...

Do not forget to implement Array.find when working with the useSWR hook in Next.js

I have the following code: const fetcher = (url: string) => axios.get(url).then((r) => r.data); const {data} = useSWR("api/data", fetcher, {refreshInterval: 10000}) console.log(data.find(d => d.id === "123")) The API path is ...

Choose options according to a different select in VueJS Laravel

As a VueJs beginner working with Laravel, I am struggling to display categories dynamically when selecting a collection. I am making API calls using Axios, but I can't quite get it to work correctly. Any assistance would be greatly appreciated. <di ...

Issue with inconsistent error handling in Mui DateTimePicker and react-hook-form

I am currently facing an issue with a DateTimePicker component that I am trying to integrate into a form controlled by react-hook-form. The validation is straightforward - I am using the disablePast prop on the DateTimePicker to ensure that the selected da ...

In a Next.js application directory, how can you retrieve the router.asPath value within a function that utilizes the Next.js navigation feature?

import { useRoute } from "next/navigation" const route = useRoute() const updateData = () => { route.replace(route.asPath); } I attempted using next/router but it was unsuccessful ...