Asked By: Anonymous
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.
Solution
Answered By: Anonymous
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.