Emitting global events from websocket listener

前端 未结 2 469
广开言路
广开言路 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

    <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.

    0 讨论(0)
  • 2021-01-05 13:40

    Hey this should work for you better and easy

    This my example with .vue file

    yourVueFile.Vue

     <template>
    // key in your template here
    </template>
    
    <script>
    export default {
    //use the created() option to execute after vue instance is created
      created() {
        let ws = new WebSocket("yourUrl");
        ws.onopen = e => {
          ws.send(
            JSON.stringify({ your json code })
          );
    
            ws.onmessage = e => {
            let data = JSON.parse(e.data);
    
    // the this.$data get your data() options in your vue instance
                this.$data.dom = data;
    
          };
        };
      },
      data() {
        return {
           dom: core
        };
      },
      methods: {
    
      }
    };
    </script>
    
    0 讨论(0)
提交回复
热议问题