moktar
10/11/2019 - 3:57 PM

Vue 2 version

Vue 2 version

// index.html

<div id="chat">
    <ul id="message">
        <li v-for="message in messages" :key="message.id">{{ message }}</li>
    </ul>
    <form @submit="send">
        <input type="text" v-model="message">
        <button>Send</button>
    </form>
</div>

new Vue({
    el:'#chat',
    data: {
        messages: [],
        message: '',
    },
    mounted: function() {
        socket.on('chat.message', function(message) {
            this.messages.push(message);
        }.bind(this));
    },
    methods: {
        send: function(e) {
            socket.emit('chat.message', this.message);
            this.message = '';
            e.preventDefault();
        }
    }
})