Emitting global events from websocket listener

纵然是瞬间 提交于 2019-12-01 06:41:13

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.

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!