Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Advanced Vue.js - Directives, Plugins, and Render Functions Chapter 17

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

 tag will help us render a chat. As we don't need the 
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')

After that, we declare our Vue instance that will contain a chat string (to contain the chat


so far) and a message string (to contain the message we are currently writing):


new Vue({
el: '#app',
data: {
chat: '',
message: ''
}
})

We still need to define the send method, which is called upon pressing Enter in the textbox:


new Vue({
el: '#app',
data: {
chat: '',
message: ''
},
methods: {
send () {
this.appendToChat(this.message)
ws.send(this.message)
this.message = ''
},
Free download pdf