【发布时间】:2019-10-29 23:53:48
【问题描述】:
我想仅在一个特定组件中实例化与服务器的 websocket 连接。我正在使用 Vuecli、socket.io、socket.io-client 和 vue-socket.io
谷歌搜索我已经能够实例化一个全局连接,然后像下面的例子一样使用它:
/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 }));
在我的 Comenponent.vue 中,我可以使用 this.$socket. 来引用 websocket 实例。
<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>
为了将 websocket 放在单个组件中,我尝试了以下方法:
/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>
根据上述代码的状态,我可以使用this.sock.emit() 向服务器发送数据,但我不知道如何监听来自服务器的消息。
提前感谢您的帮助。
项目的github链接:https://github.com/anatolieGhebea/simpleDocBuilder
组件在 /frontend/src/views/Editor.vue 下
【问题讨论】: