T
T
TinyZerg2018-06-09 17:14:06
Vue.js
TinyZerg, 2018-06-09 17:14:06

Vue.js websocket plugin?

Hello. Wrote a plugin for working with the SockJS library on the client side.

import SockJS from 'sockjs-client';

export default {
    install(Vue, connection) {
        let socket;

        if (!connection) throw new Error("[websocket plugin] cannot locate connection")

        if (typeof connection == 'string') {
            socket = new SockJS(connection);
        } else {
            socket = connection;
        }

        Vue.prototype.$socket = socket;

        Vue.mixin({
            beforeCreated() {
                if (this.$options["socket"]) {
                    let conf = this.$options.socket;
                    Object.keys(conf).forEach((key) => {
                        switch(key)
                        {
                            case 'onopen':
                                this.$socket.onopen = conf[key].bind(this);
                                break;
                            case 'onclose':
                                this.$socket.onclose = conf[key].bind(this);
                                break;
                            case 'onerror':
                                this.$socket.onerror = conf[key].bind(this);
                                break;
                            case 'onmessage':
                                this.$socket.onmessage = conf[key].bind(this);
                                break;
                        }
                    });
                }
            },
            beforeDestroy() {

            }
        });
    }
}

now I use the socket property in the App.vue component and define the functions onopen, onmessage, etc. in it:
export default {
    name: 'app',
    socket: {
      onopen() {
        console.log('OPEN');
      },
      onmessage(msg) {
        console.log(msg);
      },
      onclose(e) {
        console.log(e);
      },
      onerror(e) {
        console.log(e)
      }
    }
  }

Everything would be fine, everything works, when a connection is established I receive an OPEN message in the console, when a message comes from the server, I receive the text of the message in the console.
But ran into a problem. In a certain component (chat.vue) I wanted to send a message in the created() hook. Wrote something like this:
created() {
            this.$socket.send("Hello");
        },

I get an error that the connection has not yet been established at the time send() was called. Indeed, created() on the component is called before the onopen() function binding on the socket: {} property is called on the root component.
Question: am I implementing the plugin incorrectly, or should I work with sockets in vue differently?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question