zlotte
zlotte

Reputation: 221

SocketIO data to VueJS

How can I place data results from socketIO to the Vue instance ? This is my code:

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>

At the moment I get no errors and also data is not displayed.

Upvotes: 1

Views: 63

Answers (1)

edwin
edwin

Reputation: 2841

This should work:

let socket = io();

new Vue({
    el: '#playersCounter',
    data: {
        playerCounter: users
    },
    created: function() {
        socket.on('user-connected', (data) => {
            this.playerCounter = data.count;
            console.log(data.count);
        });
        socket.on('user-disconnected', (data) => {
            this.playerCounter = data.count;
            console.log(data.count);
        });
  },
});

Upvotes: 1

Related Questions