I am trying to use vue in combination with sockets. However I cannot seem to get the vue application to accept socket events. I am following the tutorials found online and they tell me that the example below should work. However it doesn't and I am puzzle why.
What I do know:
- The sockets are connected. The server side triggeres the connection event
- I can emit an event from app.vue by using
this.$socket.emit('mounted', 'something') - I cannot received events under the
socketssection. None of the connect, disconnect or test are triggered.
Why is the sockets part not working?
My server.js:
const io = require('socket.io')(8000);
io.on('connection', function(socket) {
console.log(`A user connected with socket id ${socket.id}`)
socket.on('mounted', function(data) {
console.log('data', data)
io.emit('test');
})
socket.on('disconnect' , function(){
console.log('User left page');
});
});
my main.js
import Vue from 'vue'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'
import SocketIO from "socket.io-client"
Vue.config.productionTip = false
Vue.use(new VueSocketIO({
debug: true,
connection: SocketIO('http://localhost:8000'),
})
);
new Vue({
render: h => h(App),
}).$mount('#app')
the script in my app.vue
<script>
import HelloWorld from './components/HelloWorld.vue'
//var socket = io();
export default {
name: 'App',
components: {
HelloWorld
},
mounted () {
console.log('mounted')
this.$socket.emit('mounted', 'something')
},
sockets : {
test: function(data){
console.log('test triggered', data)
},
connect() {
console.log('connected')
},
disconnect() {
console.log("server disconnected");
},
}
}
</script>