MetinSeylan / Vue-Socket.io

😻 Socket.io implementation for Vuejs and Vuex
https://metin.sh
MIT License
3.95k stars 496 forks source link

connect function dos not trigger #332

Open nick-bai opened 2 years ago

nick-bai commented 2 years ago

my code like this main.js

import VueSocketIO from 'vue-socket.io'
import config from '@/config/index'

Vue.use(
  new VueSocketIO({
    debug: false,
    connection: config.API_URL + ':' + config.SOCKET_PORT
  })
)

chat.vue

sockets: {
    connect() {
      this.$message.success('connect success')
    },
}

I want make sure that the socket is connected and then to register user. but when i refresh web , sometimes the connect function works and sometimes it dos not work. when I use chrome and open debug(F12), it works every time. I use the newest version 3.0.10 I try to use old version 3.0.5 and 3.0.7 it still dos not work.

ghandhikus commented 2 years ago

It's a race condition. If a component is not mounted before the socket connects, it won't trigger connect. If the socket connects after it's mounted it will trigger the events. The same goes for every event like reconnect or disconnect. I do believe the events should trigger but there is a workaround.

sockets: {
  connect: function () {
    this.connected();
  },
  disconnect: function () {
    this.disconnected();
  },
},

mounted() {
  // this.connect is not available until after it's mounted, due to how Vue-Socket.io is written
  if(this.$socket && this.$socket.connected) {
    this.connected();
  } else {
    this.disconnected();
  }
},

methods: {
  connected: function () {
    // do something here
  },

  disconnected: function () {
    // do something here
  },
},