消息时不触发代码"/>
[Vuejs从socket.io服务器接收消息时不触发代码
我一直在努力允许vuejs应用程序与远程独立的socket.io服务器对话。我已经设法使vuejs应用程序将消息发送到socket.io服务器(通过nodejs实例上的控制台日志确认),并且似乎正在获得响应,但似乎无法启动它基于响应的代码。
我正在以最基本的形式使用Vue-socket.io,并且我已将localhost和null添加到起源以希望排除该问题。
- 我正在localhost:3000上运行socket.io服务器
- 我正在运行vuejs应用在localhost:8888]
为什么听众不在下面的代码中触发?我也没有在app.vue中获得关于sockets.connect和sockets.customMessage的任何控制台日志。
socket.io(nodejs)服务器:
var http = require('http').createServer({
origins: ['localhost','null',null]
});
var io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('a user connected');
socket.broadcast.emit('hi, welcome to live chat');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('chatMessage', (msg) => {
console.log('chatMessage: ' + msg);
io.emit('chatMessage', msg);
});
})
http.listen(3000, () => {
console.log('listening on port 3000');
});
app.js(vuejs应用的入口):
import Vue from 'vue'
//import store from './store'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'
import SocketIO from "socket.io-client"
Vue.use(new VueSocketIO({
debug: true,
connection: 'http://localhost:3000'
}))
new Vue({
render: h => h(App)
}).$mount('#app')
App.vue:
<template>
<div>
hello chat app
<input type="text" v-model="message"/>
<button @click="clickButton()">Send Msg</button>
</div>
</template>
<script>
export default {
name: "Home",
sockets: {
connect: function () {
console.log('socket connected')
},
chatMessage: function(data) {
console.log('this method was fired by the socket server. eg: io.emit("chatMessage", data)')
}
},
methods: {
clickButton: function () {
console.log('button clicked');
console.log(this.message);
// $socket is socket.io-client instance
this.$socket.emit('chatMessage', this.message)
}
},
data: () => {
return {
message: '',
};
},
computed: {
},
mounted() {
this.$socket.on('chatMessage',data => {
console.log('listen fired')
console.log(data);
});
}
}
</script>
回答如下:您能否尝试将此配置放入app.js
只需添加一个连接选项,并在实例化VueSocketIO
实例时使用它。
const options = { path: '/socket.io/' }; //<--
Vue.use(new VueSocketIO({
debug: true,
connection: 'http://localhost:3000',
options //<--
})
);
然后重试?如果它不起作用,我可以发布我的解决方案。
更多推荐
[Vuejs从socket.io服务器接收消息时不触发代码
发布评论