Blog>
Snippets

Vue.js Plugin for Real-time Data with Websockets

Develop a plugin that sets up a WebSocket connection and provides components with real-time data capabilities.
Vue.createApp({
  data() {
    return {
      socket: null,
      message: null
    };
  },
  created() {
    this.socket = new WebSocket('ws://localhost:8080');
    this.socket.onmessage = (event) => {
      this.message = event.data;
    };
  }
}).mount('#app');
This JavaScript code snippet is used to create a new Vue application with a WebSocket connection. It sets up a Vue data property for 'socket' and 'message'. The 'created' hook is used to initialize the WebSocket connection to a given URL (in this case, 'ws://localhost:8080') and define an event listener for receiving messages. When a message is received, it updates the 'message' data property with the latest real-time data received.
<div id="app">
  <p>Latest Message: {{ message }}</p>
</div>
This HTML snippet defines a Vue app mount point with an ID of 'app'. It uses Vue's template syntax to display the latest message received from the WebSocket connection within a paragraph tag.
#app {
  font-family: 'Arial', sans-serif;
  color: #333;
}
This CSS snippet provides basic styling for the Vue app mount point. It sets the font to Arial and the text color to a dark gray.