vuejs - share websocket connection between components vuejs - share websocket connection between components vue.js vue.js

vuejs - share websocket connection between components


Create new js file (let's say "/services/ws.js"). Create instance of websocket.

const WS = new WebSocket('ws://localhost:8080');export default WS;

And then in your Vue Component import it.

<script> import WS from '../services/ws'; export default {   // here WS is your websocket instance } </script>

This is a simpliest way to share data between components (here you simply share WS instance created in another module). You also can fit MVC-style on it, keeping all logic in controllers (other modules) instead of Vue methods.


Using a Vue mixin or plugin makes this a lot easier, like this one:

https://github.com/icebob/vue-websocket

It initializes one socket and shares among all components, also has easy way of adding event handlers per component so you get good modularization.

It isn't too difficult to modify it to use native websockets if you don't want to use socket.io; or you can use this one, though I don't like the syntax as much:

https://www.npmjs.com/package/vue-native-websocket