[Vuejs]-Handle multiple sockets in a Vue project

-1👍

This could be as simple as just connecting two sockets and setting up their respective listeners. From a quick glance, most of what vue-native-socket accomplishes (in the context of the question) can be achieved using a vuex store as well, or writing your own plugin, or both!

Here’s a simple solution:

store.js

const state = {
  signalSocket: undefined,
  dataSocket: undefined
}

const getters = {
  signalSocket: state => state.signalSocket,
  dataSocket: state => state.dataSocket,
}

const mutations = {
  signalSocket (state, v) {
    state.signalSocket = v
  },
  dataSocket (state, v) {
    state.dataSocket = v
  }
}

export default new Vuex.Store({
  state,
  getters,
  mutations
})

App.vue

<template>
  ...
</template>

<script>
export default {
  computed: {
    signalSocket: {
      get () { return this.$store.getters.signalSocket },
      set (v) { this.$store.commit('signalSocket', v) }
    },
    dataSocket: {
      get () { return this.$store.getters.dataSocket },
      set (v) { this.$store.commit('dataSocket', v) }
    }
  },
  mounted () {
    this.signalSocket = new WebSocket('...')
    this.dataSocket = new WebSocket('...')
    ...
  }
}
</script>

If you want this variable to be available everywhere, much like vue-socket-native, you could add the following to your main.js

main.js

import Vue from 'vue'
import Store from './store'

Vue.use({
  install (Vue, options) {
    Object.defineProperty(Vue.prototype, '$signalSocket', {
      get () {
        return store.getters.signalSocket
      },
      set (v) {
        return store.commit('signalSocket', v)
      }
    })
    Object.defineProperty(Vue.prototype, '$dataSocket', {
      get () {
        return store.getters.dataSocket
      },
      set (v) {
        return store.commit('dataSocket', v)
      }
    })
  }
})

Leave a comment