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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With