How to do it...

For this recipe, we need a server and a browser that will act a client. We will not build a server; instead, we'll use an already existing server that just echoes whatever you send to it via WebSockets. So, if we were to send the Hello message, the server would respond with Hello.

You will build a chat app that will talk to this server. Write the following HTML code:

<div id="app">  <h1>Welcome</h1>  <pre>{{chat}}</pre>  <input v-model="message" @keyup.enter="send"></div>

The <pre> tag will help us render a chat. As we don't need the <br/> element to break a line, we can just use the n special character that means a new line.

For our chat to work, we first have to declare our WebSocket in the JavaScript:

 const ws = new WebSocket('ws://echo.websocket.org') ...

Get Vue.js 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.