SolvedVue Socket.io Emit socket event from vuex store

Hi again, can you give an example how to emit an event from a vuex store action

14 Answers

✔️Accepted Answer

ma53
120

Originally posted this in #85 but I thought I'd post it here too in case anyone on the chain might find it useful.

Your mutations and actions can reference the root Vue instance via this._vm. So, this is the method I've been using:

someAction(context, payload) {
    this._vm.$socket.emit('someEvent', someData);
}

Avoids instantiating a new Vue instance every time you need to emit an event.

Other Answers:

Temporarily we can use (new Vue()).$socket.emit(). I know, it's ugly but is better than nothing.

While the (new Vue()).$socket.emit workaround is working, I'm currently using this method:

in store.js:

...snip...
state: {
    io: {}
},
mutations: {
    setSocket: (state, socket) => {
      state.io = socket
    }
}
...snip...

in App.vue (or whatever root component you are using)

...snip...
import store from './store'
export default {
  beforeCreate() {
    store.commit('setSocket', this.$socket)
  },
...snip...

That's how the $socket object gets saved to Vuex so that you can access it via context.state.io.

More Issues: