Emitting global events from websocket listener

前端 未结 2 478
广开言路
广开言路 2021-01-05 12:52

I want to contribute to a project - it\'s written in Vue, and I am a beginner in Vue.

I have two components - Setup and MainApp

Bot

2条回答
  •  独厮守ぢ
    2021-01-05 13:15

    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

    
    
    
    

    And here is a working example.

提交回复
热议问题