SocketIO数据到VueJS

时间:2019-03-13 22:21:48

标签: javascript vue.js socket.io

如何将数据结果从socketIO放置到Vue实例?这是我的代码:

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>

此刻我没有错误,也没有显示数据。

1 个答案:

答案 0 :(得分:1)

这应该有效:

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