Emitting global events from websocket listener

There's no need for a socket specific component in this case. What I have done in the past on a couple projects is implement an API or store object that handles the socket messages and then import that API or store into the components that need it. Also in a similar answer, I show how to integrate a WebSocket with Vuex.

Here is an example that combines the concept of using Vue as an event emitter with a web socket that can be imported into any component. The component can subscribe and listen to the messages it wants to listen to. Wrapping the socket in this way abstracts the raw socket interface away and allows users to work with $on/$off subscriptions in a more typically Vue fashion.

Socket.js

import Vue from "vue"

const socket = new WebSocket("wss://echo.websocket.org")

const emitter = new Vue({
  methods:{
    send(message){
      if (1 === socket.readyState)
        socket.send(message)
    }
  }
})

socket.onmessage = function(msg){
  emitter.$emit("message", msg.data)
}
socket.onerror = function(err){
  emitter.$emit("error", err)
}


export default emitter

Here is an example of that code being used in a component.

App.vue

<template>
  <ul>
    <li v-for="message in messages">
      {{message}}
        </li>
    </ul>
</template>

<script>
    import Socket from "./socket"

    export default {
        name: 'app',
        data(){
            return {
                messages: []
            }
        },
        methods:{
          handleMessage(msg){
             this.messages.push(msg) 
          }
        },
        created(){
            Socket.$on("message", this.handleMessage)
        },
        beforeDestroy(){
            Socket.$off("message", this.handleMessage)
        }
  }
</script>

And here is a working example.