metinseylan / vue-socket.io Goto Github PK
View Code? Open in Web Editor NEW😻 Socket.io implementation for Vuejs and Vuex
Home Page: https://metin.sh
License: MIT License
😻 Socket.io implementation for Vuejs and Vuex
Home Page: https://metin.sh
License: MIT License
Hello
I find the SOCKET_
prefix for mutations somewhat counterintuitive. I didn't know this library and came across these strange mutation names in our code which appeared to make no sense.
I would prefer to define a module that is namespaced and would handle the socket requests.
So instead of
const store = new Vuex.Store({
state: {
someArray: [],
},
mutations: {
// SOCKET_ prefix handles SOCKET requests
SOCKET_rental: (state, msg) => {
...
},
},
});
we can optionally define a SOCKET submodule by passing the module name as 4th parameter
Vue.use(VueSocketio, url, store, 'SOCKET');
const store = new Vuex.Store({
state: {
someArray: [],
},
modules: {
SOCKET: {
// this submodule handles SOCKET requests
namespaced: true,
mutations: {
rental: function rental(state) {
console.log('SOCKET/rental', state);
},
},
},
}
});
Hi! I'm trying to register custom events dynamically.
Example
const entity = isAdmin ? 'administrator' : 'user'
this.$socket.on(`${entity}Online`, () => ....)
Some ways to solve the issue:
// ... emitter class definition
const emitter = new Emitter
export default emitter
Than I can import it in my code
import Emitter from 'vue-socket.io/src/Emitter'
Emitter.addListener...
BTW, I can make pull request
I wrote like this on the server side:
io.emit('test', 'param1', 'param2', 'param3')
I can get all the three arguments when using socket.io-client
socket.on('test', function () {
console.log(arguments)
})
// result:
["param1", "param2", "param3"]
But I can only get the first argument with vue-socket
sockets: {
test: function () {
console.log(arguments)
}
}
// result:
["param1"]
Hi there,
I used vue-cli to create the standard webpack scaffolding.
I'm using vue2 and vue-socket.io.
Running on the dev server, everything works perfectly. But when I build and run the built server, I get:
build.js:2Uncaught ReferenceError: f is not defined(…)
The problem isn't there when I don't include vue-socket.io (but then I can't use this awesome library)
Vue-Socket.io not working mobile
when session is changed , what can i do to refresh the connection
Hi to all
Get error in IE11: SCRIPT5009: "Proxy" is not defined. File: eval code (4200), string: 1, column: 30095. Sample of code there :
t.prototype.$socket=r.Socket,t.mixin({beforeCreate:function(){var t=this,e=this.$options.sockets;this.$options.sockets=new Proxy({},{set:function(e,n,r){return a.default.addListener(n,r,t),e[n]=r,!0},deleteProperty:function(e,n){return a.default.removeListener(n,t.$options.sockets[n],t),delete e.key,!0}})
Error is on this.$options.sockets=new Proxy
moment. How to solve this ?
Also I`m using babel-polyfill to make promises work on IE
On this page: http://metinseylan.com/vuesocketio/ When I click "Join chat" button nothing happens.
I went to the console and saw this: Failed to load resource: the server responded with a status of 404 (Not Found)
.
Thanks for building this.
Is possible to connect inside a component? I mean, not in main.js but in a module, something like Login.vue
Hi, thank you for your work in this package.
I'm not been able to listning socket events on vuex actions , tell me if i'm doing it wrong .
vuex action function :
socket_myEvent: (context) => {
//some code
}
socket.io emit
socket.emit('myEvent');
thanks
SOS!!! The server-end can receive the event emitted by client-end, but the client-end can't receive the event from server-end. I show my code as below:
// client.vue (client-end)
<template>
...
</template>
<script>
export default {
sockets: {
connect: function () {
console.log('socket connected'); // This cmd dosn't works
},
serverEmit: function (msg) {
console.log("Message:"+msg); // This cmd dosn't works
}
},
methods: {
trigger () {
this.$socket.emit('clientEmit', "I'm a message from client."); // This cmd works well
}
}
}
</script>
// server.js(server-end)
io.on('connection', (socket) => {
console.log('Socket connect successful.'); // This cmd works well
socket.on('clientEmit', (msg) => {
console.log("Message: " + msg);
socket.emit('serverEmit', "I'm a message from server."); // This cmd works well
});
});
I think the option 'sockets' is not useful in vue2.0 anymore.
Hello,
Currently, you can trigger vuex mutations with the "SOCKET_" prefix and this is nice !
But sometime, socket events must do more that just change the vuex state. for me it's also very important to be able to trigger Vuex actions by a similar way. Somehting like "event-name" triggering "socketEventName" action.
When I try to use vue-socket io like this :
Vue.use(VueSocketIo, SocketIoConnection, UsersStore);
Vue.use(VueSocketIo, SocketIoConnection, ProjectsStore);
ProjectStore doesn't receive message, expect if I comment first Vue.use(...)
Thanks for your help.
i try to use this.$socket.to(roomId).emit('sendchat_msg', data)
but console.log tell this msg
Uncaught TypeError: this.$socket.to is not a function
how do i use it
ps. sry for my bad english
All custom handlers added in "native" style wont work:
MySocket.on('myEvent',()=>{
console.log('It will never fired');
})
I think it happens because you redefine the native function Socket.onevent
I solved it like this:
onEvent() {
this.Socket.onevent = (packet) => {
Emitter.emit(packet.data[0], packet.data[1]);
if (this.store) this.passToStore('SOCKET_' + packet.data[0], packet.data[1])
};
let _this = this;
let nativeEvents = ["connect", "error", "disconnect", "reconnect", "reconnect_attempt", "reconnecting", "reconnect_error", "reconnect_failed", "connect_error", "connect_timeout", "connecting", "ping", "pong"]
nativeEvents.forEach((value) => {
_this.Socket.on(value, (data) => {
Emitter.emit(value, data);
if(_this.store) _this.passToStore('SOCKET_'+value, data)
})
})
for (let event in this.Socket._callbacks) {
this.Socket._callbacks[event].forEach(fn => {
if(!nativeEvents.includes(event)){
Emitter.addListener(event, fn);
}
})
}
this.Socket.on = function (event, fn) {
Emitter.addListener(event, fn);
}
this.Socket.off = function (event, fn) {
Emitter.removeListener(event, fn);
}
}
Hello,
I just installed the package and set it up in my main.ts (yes typescript) as:
import * as VueSocketio from 'vue-socket.io';
import * as socketio from 'socket.io-client';
Vue.use(VueSocketio, 'http://socketserver.com:1923');
var vm = new Vue({
sockets:{
connect: function(){
console.log('socket connected')
},
customEmit: function(val){
console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
}
}
});
But my compiler and complains that:
./src/main.ts
(43,1): error TS2345: Argument of type '{ sockets: {}; router: VueRouter; store: Store<{ AppName: string; UserID: number; Crumb: string; ...' is not assignable to parameter of type 'ComponentOptions'.
Object literal may only specify known properties, and 'sockets' does not exist in type 'ComponentOptions'.
It would be great if vm.$socket.emit()
would allow for broadcasting to all other clients in one way or another, e.g. following the socket.io API like vm.$socket.broadcast.emit()
.
My current workaround is to first emit from Vue, then broadcast using the original client on the server.
if component that includes socket events has a conditional rendering with v-if after rerender event will be called twice, after next rerender - three times and etc.
Example:
ComponentA
<template>
<component-b v-if="showB"></component-b>
</template>
<script>
import ComponentB from './B.vue'
export default {
components: { ComponentB },
data () {
return { showB: false }
},
created () {
setInterval(() => {
this.showB = !this.showB
}, 1000)
}
}
</script>
ComponentB
<template>hello</template>
<script>
export default {
sockets: {
message (message) {
console.log(message)
}
}
}
</script>
I can make a PR that fixes this issue
Hi, when I use vue-socket.io 2.0.0 in my project that is building by vue 2.0, an error occurred that Uncaught TypeError: Cannot read property 'BlobBuilder' of undefined in chrome console. I don't know why. Please help me. Q&A!
How force to use websocket ?
On the server node with socket.io :
import * as socket from 'socket.io'
const port = 1337
const io = socket(port, {
transports: ['websocket']
})
In my app electron-vue i have this error :
http://localhost:4100/socket.io/?EIO=3&transport=polling&t=Lmnk47U 400 (Bad Request)
Sry for my english
I'm sorry but my Issue isn't closed so I must re-open a new one ...
Here is my webpack.config.js
var config = {
entry: {
app: ['./app/appLogin.js']
},
output: {
path: __dirname + '/public/js',
filename: 'preapp-bundle.js'
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel'
},{
test : /\.vue$/,
loader : 'vue'
}]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress : {
warnings : false
},
mangle : false
})
]
}
Here is my main.js
import Vue from 'vue'
import VueSocketio from 'vue-socket.io';
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import PreApp from './views/components/PreApp.vue'
Vue.use(VueSocketio, 'http://localhost');
Vue.use(VueResource)
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
routes: [{
path: '/',
component: require('./views/components/PreApp.vue')
}]
});
new Vue({
el: '#preappvue',
router: router,
sockets: {
connect: function() {
console.log('socket connected')
},
customEmit: function(val) {
console.log('this method fired by socket server. eg: io.emit("customEmit", data)')
}
},
render: h => h(PreApp)
})
And i've still the problem of BloBuilder undefined. :(
var i = e.BlobBuilder || e.WebKitBlobBuilder || e.MSBlobBuilder || e.MozBlobBuilder,
Hi again, can you give an example how to emit an event from a vuex store action
At the moment the package.json still references to an old Build.js that has been updated a month ago. The build.js should be rebuild so you directly have the new version of Vue-Socket.io
Refresh the browser, will have to listen to a number of repeated socket events. Refresh, how to maintain socket connection or how to close the connection
Hi, I have never used socket.io. I am struggling with setting up Vue-Socket.io with the official Vue webpack template (working locally). I am getting the following errors in the console:
I am also using vue-router, I hope is not the cause of this problem.
The main.js file:
import Vue from 'vue';
import VueSocketio from 'vue-socket.io';
Vue.use(VueSocketio, 'http://http://localhost:4000/'); // Is this correct?
Thanks!
Binding the socket events is not working correctly on vue^2.0.0.
vuejs/vue@71a0f3e#diff-a3983d8041c692bde114459c55b587ebL18
I think this.$options.hasOwnProperty("sockets")
should change to this.$options["sockets"]
for the prototyped property just like other codes in vuejs.
I don't understand between Vuex Actions and Mutations with sockets:
I fully understood this #42 (Actions are called when socket server send an event).
But how to uses Mutations with sockets?
Thanks!
Hi! @MetinSeylan
Thank you for this great package!
In a normal flow, works pretty awesome!
But in my flow, I need start the socket connection when the application starts, I put the connection in my main.js
... ok until here... when I open the application window I can see the connection was made in the server console.
I want to use the connection that was opened when the application was started in other application places... Eg. on the dashboard component and set his own listeners on the sockets { }
.
This is possible? you know a way to do that?
Best regards
Hi,
It's possible to have multiple socket.io connections (for example on differents servers) ?
In my case, I work in a microservices architecture and some of them have a socket.io server.
With the current mode of your library, I can't use this for my projects.
Thanks
Hello,
in version 2.1.* you add Proxy object, and after that my app not work in IE 11, becouse in IE 11 is no Proxy object.
E.g.
store.commit('enterQueue');
enterQueue: function(state) {
state.socket.emit("enterQueue");
// bunch of other code
}
Right now I'm working around it like this
const socket = io('http://localhost:3000');
const store = new Vuex //blah blah
Vue.use(VueSocketio, socket, store);
So I can use the socket global variable from within the store, as well as the socket functionality provided from this package
SOCKET_ mutations are very useful but is there a way to make possible using them in namespaced store modules of Vuex? We can't catch even CONNECT inside the module, because it needs a module prefix. Or I don't understand something...
Hello,
How to create a custom socket mutation? and how to use it ?
Hello. I do not know much english, so I use a translator. I have extensive experience in backend, but little experience frontend.
I have a simple project and easy task, I do not need to use webpack or other.
That's where I started:
<div id="app">
<input v-model="name"><br>
<textarea v-model="message"></textarea><br>
<button @click.prevent="send">Send</button>
</div>
<script src="js/vendor/vue.js"></script>
<script src="js/vendor/build.js"></script>
<script src="js/main.js"></script>
console.log(VueSocketio);
Vue.use(VueSocketio, 'http://host:8080');
Object {default: Object, __esModule: true}
vue.js:3450 Uncaught TypeError: plugin.apply is not a function
Of course I was looking for ways to solve this problem, try install webpack and rebuilt the project - did not help.
Hi,
Vue--Socket.io not work with Cordova ?
The details of this question are documented in this stackoverflow post. It seemed like too much to put here.
As a side note, it would be cool if you had more examples including a dirt-simple example in which only localhost is used along with a button and a custom socket.
you have this example in your readme:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
connect: false,
message: null
},
mutations:{
SOCKET_CONNECT: (state, status ) => {
state.connect = true;
},
SOCKET_USER_MESSAGE: (state, message) => {
state.message = message;
}
},
actions: {
otherAction: (context, type) => {
return true;
},
socket_userMessage: (context, message) => {
context.dispatch('newMessage', message);
context.commit('NEW_MESSAGE_RECEIVED', message);
if (message.is_important) {
context.dispatch('alertImportantMessage', message);
}
...
}
}
})
how will connect
become false
again when e.g. the socket server crashes? Is there a disconnect event on the client?
Great library 👍
Wondering how I might implement the sockets property into Vuex, right now I'm basically doing this to work around
let socket = io.connect('http://localhost:3000');
const store = new Vuex.Store({
state: {
user: {
loggedIn: false,
avatar: "",
displayName: ""
},
chatUsers: []
},
mutations: {
setUser (state, {loggedIn, avatar, displayName}) {
state.user.loggedIn = loggedIn;
state.user.avatar = avatar;
state.user.displayName = displayName;
},
addChatUser (state, displayName) {
if (state.chatUsers.indexOf(displayName) !== -1) return;
state.chatUsers.push(displayName);
},
remChatUser (state, displayName) {
let index = state.chatUsers.indexOf(displayName);
if (index !== -1) {
state.chatUsers.splice(index, 1);
}
}
}
})
socket.on('addUserToList', function(user) {
store.commit('addChatUser', user);
});
socket.on('remUserFromList', function(user) {
store.commit('remChatUser', user);
})
The only thing is that it's creating 2 socket connections per person
Can i use Vue-socket io in vuex file?
if it's can use how to?
Thanks
Hello is it possible to specify a different Port when doing the handshake to upgrade from HTTP to WS (or HTTPS to WSS)?
The problem is that OpenShift PaaS uses ports 80/443 for HTTP and HTTPS. However, it listens for WS/WSS traffic on 8000/8443 .
For example this code will not work for OpenShift:
if (process.env.NODE_ENV === 'production') {
Vue.use(VueSocketio, 'https://xxxxxx.rhcloud.com/socket.io/');
}
Since the code detects https it will assume that when upgrading to WSS it will use port 443 and it wont be able to complete the handshake. What I need is to specify HTTPs traffic = 443 but WSS to use 8443.
I would appreciate if someone could point me where to change socket.io client code or the vue-socket.io. THank you.
On Server
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.emit("SOCKET_USER_MESSAGE",'hi');
socket.on('emit_method', function(data){
console.log(data);
});
});
On Vuex
SOCKET_CONNECT : (state,status) => {
state.connect = true;
alert('connect with socket.io')
},
SOCKET_USER_MESSAGE : (state,message) => {
alert(message)
state.newMessage = message
}
connect is success, but i can't get message.
And in this way,it's work
sockets: {
SOCKET_USER_MESSAGE : function (data) {
console.log(data)
}
}
What did I do wrong ??
Hi,
I don't see connect_error event on sources.
I propose to fix it with :
["connect", "error", "disconnect", "reconnect", "reconnect_attempt", "reconnecting", "reconnect_error", "reconnect_failed"]
.forEach((value) => {
_this.Socket.on(value, (data) => {
Emitter.emit(value, data)
})
})
_this.Socket.io.on('connect_error', (error) => {
Emitter.emit('connect_error', error)
})
to listen connection error first time when we don't need to reconnect.
Hi,
export default {
data() {
return {
test_message: '',
};
},
mounted() {
this.user = this.$auth.user();
this.$socket.emit('test');
},
sockets: {
onTest: (test_message) => {
window.console.log(this); // {default: beforeCreate: [..], sockets: {...}}, but should be VueComponent
// this.test_message = test_message;
},
},
};
Hello :)
I have an issue when I try to move my socket.io receivers from a component to my vuex store.
I simply added a SOCKET_CONNECT event into my store mutations, and it throws an error everytime its called.
`import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const state = {
notes: [],
activeNote: {}
};
const mutations = {
ADD_NOTE (state) {
const newNote = {
text: 'New note',
favorite: false
};
state.notes.push(newNote);
state.activeNote = newNote
},
EDIT_NOTE (state, text) {
state.activeNote.text = text
},
DELETE_NOTE (state) {
state.notes.$remove(state.activeNote);
state.activeNote = state.notes[0]
},
TOGGLE_FAVORITE (state) {
state.activeNote.favorite = !state.activeNote.favorite
},
SET_ACTIVE_NOTE (state, note) {
state.activeNote = note
},
SOCKET_CONNECT () {
console.log('USER IS CONNECTED TO THE SOCKET')
}
};
export default new Vuex.Store({
state,
mutations
});
`
It's not only for the SOCKET_CONNECT event, I tried a custom event 'SOCKET_PING' and I have the same error. I had no problem when those events are located in a component.
The error is "this.store.commit is not a function".
Any ideas ?
Here is how I linked my store the Vue-Socket.io
`
import Vue from 'vue'
import store from './vuex/store'
import App from './components/App.vue'
import VueSocketio from 'vue-socket.io'
Vue.use(VueSocketio, 'http://localhost:3000/', store);
new Vue({
store,
el: 'body',
components: { App }
});
`
Thanks in advance :)
Hello,
I have this problem width ie ;
L’objet ne gère pas la propriété ou la méthode « startsWith »
Hey,
Yes I know, that is the exact same problem that other issues but I tried to fix it with the uglify.mangle options but that doesn't work.
So, I use socket.io on my Express server and I try to use Vue-socket.io in my app.js like this
import VueSocketio from 'vue-socket.io';
Vue.use(VueSocketio, 'http://socketserver.com:3000'); // i'm listening on port 3000
new Vue ({
sockets : {
connect : function() {
console.log('connected to iosocket');
}
}
})
But when I webpack my project I've the error property blobuilder of undefined.
Does Vue-Socket.io need any dependencies in blob ?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.