How to Use Websockets With Your Vue Projects

Feb 18, 2021

WebSockets are a great tool for when you want to show real time changes in data. For example, a server can push stock market price changes to the client rather than the client needing to ask for the changes via a HTTP request. With this being said, below you will find an example of a simple Vue application that shows the current time to the user and where the user can send a simple message to the websocket.

  const app = new Vue({
    data: () => ({ time: null }),
    template: `
      <div>
        <h2>{{time}}</h2>
      </div>
    `,
    mounted: function(){
      let connection = new WebSocket('ws://localhost:3000/');
      connection.onmessage = (event) => {
        // Vue data binding means you don't need any extra work to
        // update your UI. Just set the `time` and Vue will automatically
        // update the `<h2>`.
        this.time = event.data;
      }
    }
  });
  app.$mount("#content");

Below is an example websocket server that you can use with the above Vue code.

"use strict";

const serverPort = 3000;
const express = require("express");
const http = require("http");
const WebSocket = require("ws");

const app = express();
const server = http.createServer(app);
const websocketServer = new WebSocket.Server({ server });

//when a websocket connection is established
websocketServer.on("connection", (webSocketClient) => {
  // send feedback to the incoming connection
  webSocketClient.send("The time is: ");
  setInterval(() => {
    let time = new Date();
    webSocketClient.send("The time is: " + time.toTimeString());
  }, 1000);
});

//start the web server
server.listen(3000, () => {
  console.log("Websocket server started on port 3000");
});

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!