简体   繁体   中英

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.

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);
        });
  },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM