IT이야기

웹 주소록 수신기에서 전역 이벤트 방출

cyworld 2022. 4. 17. 12:39
반응형

웹 주소록 수신기에서 전역 이벤트 방출

나는 프로젝트에 기여하고 싶다 - 그것은 Vue로 쓰여져 있고, 나는 Vue에서 초보자다.

나는 두 가지 구성 요소가 있다.Setup그리고MainApp

둘 다 웹세트의 다른 메시지에 기초하여 일부 상태를 업데이트해야 할 것이다.어떤 웹셋 메시지는 전자에 영향을 미치고, 어떤 것은 후자에 영향을 미칠 것이다.

Vue는 서비스를 몰라서 그냥 비어 있는 사용자 지정 구성 요소를 만들어야겠다고 생각했다.<template>.웹세트를 그곳에서 인스턴스화한 다음, a를 발행한다.this.emit()청취자에게 새로운 메시지가 나타날 때마다

다른 두 구성 요소 모두 방출 소리를 듣고 반응할 수 있을 것이다.

아쉽게도 웹소켓 컴포넌트를 작동시킬 수가 없다.

main.js:

import Ws from './WsService.vue';
//other imports

const routes = [
  //routes
]


const router = new VueRouter({
  routes // short for `routes: routes`
})   

const app = new Vue({
  router
}).$mount('#app')
//I thought this to be the way to instantiate my webSocket service:
const WsService = new Vue({
  el: '#WsService',
  components: { Ws }
});

인덱스.포인트

  <body>
    <div id="app">
      <div id="WsService"></div>
      <router-link to="/setup">Setup</router-link>
      <router-link to="/main-app">Main App</router-link>
      <router-view></router-view>
    </div>
    <script src="/dist/demo-app.js"></script>
  </body>

웹 사이트 "서비스":

<template>
</template>

<script>
const PORT_LOCAL = 9988; 
var ws = new WebSocket("ws://localhost:" + PORT_LOCAL);
ws.onopen = function() {
     ws.send('{"jsonrpc":"2.0","id":"reg","method":"reg","params":null}');
};

ws.onerror =  function(e) {
      console.log("error in WebSocket connection!");
      console.log(e);
};

export default {

  data() {
    return {
    }
  },

  created() {
    var self = this;
    ws.onmessage =  function(m) {
          var msg = JSON.parse(m.data);
          switch(msg.id) {
            // result for address request
            case "reg": 
              self.$emit("reg_received", msg.result);
              break;
            case "send":
              self.$emit("send_received", msg.result);
              break;
            case "subscribe":
              self.$emit("subscribe_received", msg.result);
              break;
            default:
              console.log(msg);
              break;
          }
    }
  },

  methods: {
  },

  send(id, method, params) {
     ws.send('{"jsonrpc":"2.0","id":"' + id + '","method":"' + method + '","params":null}');

    }
  }

}
</script>

메인 앱에서 예를 들어 보내기(이 방법이 효과가 있는 것 같음):

 import WsSvc from './WsService.vue';
 export default {
   data() {
     //
   },
   subscribe() {
     let jsonrpc = "the jsonrpc string";
     WsSvc.send(jsonrpc);
   }
 }

듣기emit:

 export default {
   data() {
     //
   },
   created() {
     this.$on("reg_received", function(result){
       //do smth with the result
     });

   }
 }

이 구성을 바탕으로created훅은 실제로 전화를 받지 않는다. 그래서 나는 결코 그 곳을 치지 않을 것이다.onmessage경청하는 사람맞춤 구성 요소를 갖추게 된 이유는, 그 구성 요소에 접근할 수 있기 때문이었습니다.emit기능을 발휘하다

내가 필요 이상으로 복잡하게 만드는 것 같은데, 아직 제대로 맞추지 못했어.해결책은 이 접근법을 따를 필요가 없다.

이 경우에는 소켓 특정 구성품이 필요하지 않다.내가 과거에 몇 개의 프로젝트에서 한 일은 소켓 메시지를 처리하는 API나 저장 객체를 구현한 다음, API를 가져오거나 저장하거나 그것이 필요한 구성요소로 저장하는 것이다.또한 비슷한 답변으로 웹소켓을 Vuex와 통합하는 방법을 보여준다.

어떤 구성요소로도 가져올 수 있는 웹 소켓과 함께 Vue를 이벤트 이미터로 사용하는 개념을 결합한 예가 여기에 있다.컴포넌트는 자신이 듣고 싶은 메시지를 구독하고 들을 수 있다.이러한 방식으로 소켓을 감싸면 원시 소켓 인터페이스가 추상화되며 사용자가 보다 일반적인 Vue 방식으로 $on/off 구독으로 작업할 수 있다.

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

구성 요소에서 사용되는 코드의 예는 다음과 같다.

앱뷰

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

그리고 여기 일하는 예가 있다.

이봐, 이건 널 위해 더 잘 될거야, 그리고 쉽게.

이것은 .vue 파일을 사용한 내 예

yourVueFile.부에

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

참조URL: https://stackoverflow.com/questions/46677360/emitting-global-events-from-websocket-listener

반응형