Steven
Steven

Reputation: 141

vue socket connection not triggered

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:

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>

Upvotes: 4

Views: 3004

Answers (1)

rrobben
rrobben

Reputation: 483

If you are running a version greater than 3.0.7 you need to uninstall vue-socket.io and install version 3.0.7 instead.

I had this exact problem and upon inspecting the vue-socket.io NPM page I saw that they had released 2 new updates (3.0.8 and 3.0.9). I was running 3.0.9 in my project. I uninstalled the vue-socket.io 3.0.9 version and installed the 3.0.7 version which worked immediately without changing any code. My other project where socket.io did work was running version 3.0.7 as well.

I am not sure if I did something wrong on my end but I followed the exact documentation of their newer version and I couldn't make it work. So for now I assume it is an error on their end.

Upvotes: 3

Related Questions