[Vuejs]-How do I pass websocket instance to vue.js components and then call send() on it?

0👍

Try to create the socket instance in the global window scope. It will be created before Vue app is mounted and can be accessed across your app.

App.vue

<script>
 window.socket = new WebSocket('ws://localhost:3000/websocket');
 export default {
    name: 'app'
 };
</script>

HelloWorld.vue

methods: {
  send: () => {
    window.socket.addEventListener('open', () => {
      window.socket.send('Hello Server!');
    });
  },
},

Leave a comment