Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs - share websocket connection between components

Getting started with a small vuejs application. How do I open a websocket connection let's say in the root component and reuse the same connection in other components?

I want components to be able to send and receive over the same connection. Those components are gonna be tied to routes so that there is no straight parent - children relationship between the root component and the component rendered for a route.

App.vue:

<template>
  <div id="app">
    <h1>My app</h1>
    <router-link to="/">P&L</router-link>
    <router-link to="/other-page">other page</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {

  name: 'app',
  data () {
    return {
      ws: null
    }
  },

  created () {
    this.ws = new WebSocket('ws://localhost:8123/ws')
  },
  methods: {
    }
  }
}
</script>

Now I'd like to reuse ws in other-page as to not reconnect every time I change route.

like image 444
neric Avatar asked Mar 23 '17 17:03

neric


2 Answers

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.

like image 199
vovchisko Avatar answered Nov 17 '22 00:11

vovchisko


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

like image 1
Halcyon Avatar answered Nov 16 '22 23:11

Halcyon