I want to instantiate a websocket connection with the server, only in one particular component. I'm using Vuecli, socket.io, socket.io-client and vue-socket.io
Googling around I've been able to instantiate a global connection and then use it like in the following example:
/main.js
[...]
import socketio from 'socket.io-client';
import VueSocketIO from 'vue-socket.io';
[...]
export const SocketInstance = socketio('http://localhost:8080');
Vue.use( new VueSocketIO( {"debug":true, "connection":SocketInstance }));
and in my Comenponent.vue I can use this.$socket. to refer to the websocket instance.
<template>
.....
</template>
<script>
export default {
data(){
return { .... }
},
methods:{
...
// works fine
ping(){ this.$socket.emit('pingServer','hey') }
...
},
// to listen for messages from the server i'm using:
sockets: {
message(data){ console.log(data); },
serverResp(data){ console.log(data); },
}
...
}
</script>
To have the websocket in a single component I've tried the following:
/Component.vue
<template>
.....
</template>
<script>
//import lib
import socketio from 'socket.io-client';
import VueSocketIO from 'vue-socket.io';
export default {
data(){
return {
socket: null,
...
}
},
created(){
this.s = socketio('http://localhost:8080');
this.socket = new VueSocketIO( {"debug":true, "connection":s });
....
},
methods: {
// emit data does work
ping(){ this.socket.emit('pingServer','hey') }
},
// not available anymore
sockets:{
message(data){}
}
}
</script>
Per state of the above code, I can send data to server with this.sock.emit() but I can't figure out how to listen for the message coming from server.
Thanks in advance for any help.
github link of the project: https://github.com/anatolieGhebea/simpleDocBuilder
the component is under /frontend/src/views/Editor.vue