Answer the question
In order to leave comments, you need to log in
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() {
}
});
}
}
export default {
name: 'app',
socket: {
onopen() {
console.log('OPEN');
},
onmessage(msg) {
console.log(msg);
},
onclose(e) {
console.log(e);
},
onerror(e) {
console.log(e)
}
}
}
created() {
this.$socket.send("Hello");
},
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question