E
E
ezpy2017-07-10 16:32:49
Vue.js
ezpy, 2017-07-10 16:32:49

How to work with websocket in vuejs?

Hello, I have this project structure

-components
--main
--Main.vue
-App.vue
-main.js

I connect to the socket server in App.vue:
export default {
    data: function () {
      return {
        seenmoney: false,
        ws: null,
        onlinePlayers: 0,
      };
    },

    created: function() {
      var self = this;
      this.ws = new WebSocket('ws://localhost:8081/ws');
      this.ws.onopen = function() {
        console.log('WS подключенно')
      };
      this.ws.onclose = function(eventclose) {
        console.log('соеденение закрыто причина: ' + this.eventclose)
      }
      this.ws.onmessage = function(msg) {
        console.log('Сообщение ' + this.msg)
      }
    },

    methods: {
      sh: function () {
        if (this.seenmoney) {
          this.seenmoney = false;
        } else {
          this.seenmoney = true;
        }
      },
      sendmsg: function () {
        this.ws.send('тест сообщение');
      }
    }
  }

Now I can not quite understand how to send a socket message or receive from other components.
Please advise, I will be very grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kulakov, 2017-07-10
@ezpy

You can use the wrapper: https://github.com/MetinSeylan/Vue-Socket.io, it's easier with it - you can use the socket in each component. If you want to implement it yourself, then I recommend looking at the source codes of this lib, because anyway, you have to do the same thing)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question