我只想在一个特定的组件中实例化一个与服务器的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下
发布于 2019-10-29 23:53:49
在您的created()方法中(我不确定哪个正在使用socket.io客户端),但是您可以这样做
//example msg event
this.s.on("msg", (data) => { console.log("joined", data); }我实现了类似的东西,虽然我使用了混合,但您可以很容易地将其转换为单个组件。我的代码摘录(在客户端,我只是使用来自here的npm库'socket.io-client')
const io = require("socket.io-client")
export default{
data() {
return {
socket: undefined
}
},//end data
created() {
let chatUrl = "http://localhost:3000";
this.socket = io(chatUrl, {
//force websockets only - it's optional
transports: ["websocket"]
});
//socket io events
this.socket.on("join", data => {
console.log("joined ", data);
});
},//end created
methods: {
//e.g. sending a chat message
send_chat: function(message) {
this.socket.emit("chat", message);
},
},//end methods
}https://stackoverflow.com/questions/54187027
复制相似问题