😻 Socket.io implementation for Vuejs and Vuex

Overview

Patreon

Vue-Socket.io is a socket.io integration for Vuejs, easy to use, supporting Vuex and component level socket consumer managements

Demo

are you looking for old documentation? it's here

🚀 Installation

npm install vue-socket.io --save
Using Connection String
import Vue from 'vue'
import store from './store'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'

Vue.use(new VueSocketIO({
    debug: true,
    connection: 'http://metinseylan.com:1992',
    vuex: {
        store,
        actionPrefix: 'SOCKET_',
        mutationPrefix: 'SOCKET_'
    },
    options: { path: "/my-app/" } //Optional options
}))

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
Using socket.io-client Instance
import Vue from 'vue'
import store from './store'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'

const options = { path: '/my-app/' }; //Options object to pass into SocketIO

Vue.use(new VueSocketIO({
    debug: true,
    connection: SocketIO('http://metinseylan.com:1992', options), //options object is Optional
    vuex: {
      store,
      actionPrefix: "SOCKET_",
      mutationPrefix: "SOCKET_"
    }
  })
);

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')
Parameters Type's Default Required Description
debug Boolean false Optional Enable logging for debug
connection String/Socket.io-client null Required Websocket server url or socket.io-client instance
vuex.store Vuex null Optional Vuex store instance
vuex.actionPrefix String null Optional Prefix for emitting server side vuex actions
vuex.mutationPrefix String null Optional Prefix for emitting server side vuex mutations

🌈 Component Level Usage

If you want to listen socket events from component side, you need to add `sockets` object in Vue component, and every function will start to listen events, depends on object key

new Vue({
    sockets: {
        connect: function () {
            console.log('socket connected')
        },
        customEmit: function (data) {
            console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
        }
    },
    methods: {
        clickButton: function (data) {
            // $socket is socket.io-client instance
            this.$socket.emit('emit_method', data)
        }
    }
})
Dynamic Listeners

If you need consuming events dynamically in runtime, you can use `subscribe` and `unsubscribe` methods in Vue component

this.sockets.subscribe('EVENT_NAME', (data) => {
    this.msg = data.message;
});

this.sockets.unsubscribe('EVENT_NAME');
Defining handlers for events with special characters

If you want to handle 'kebab-case', or "event with space inside it" events, then you have to define it via the following way

export default {
  name: 'Test',
  sockets: {
    connect: function () {
      console.log('socket to notification channel connected')
    },
  },

  data () {
    return {
      something: [
         // ... something here for the data if you need.
      ]
    }
  },

  mounted () {
    this.$socket.subscribe("kebab-case", function(data) {
        console.log("This event was fired by eg. sio.emit('kebab-case')", data)
    })
  }
}

🏆 Vuex Integration

When you set store parameter in installation, `Vue-Socket.io` will start sending events to Vuex store. If you set both prefix for vuex, you can use `actions` and `mutations` at the same time. But, best way to use is just `actions`

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {},
    mutations: {
        "<MUTATION_PREFIX><EVENT_NAME>"() {
            // do something
        }
    },
    actions: {
        "<ACTION_PREFIX><EVENT_NAME>"() {
            // do something
        }
    }
})

Stargazers over time

Stargazers over time

Issues
  • Handle more than one namespace

    Handle more than one namespace

    The following PR contain all the changes needed in order to be able to handle more than one namespace or connection. This PR doesn't add breaking changes, so it won't be a problem for the people who's already using this package.

    To be able to use several namespace and to avoid adding breaking changes I added a key to the plugin option object called useConnectionNamespace, what this does is telling the plugin that you are going to be using more than one namespaced connection and you want to put every connection in their own $socket key. So, supposing that useConnectionNamespace option is true and you are connecting to ws://localhost/chat, your connection object will be in Vue.prototype.$socket.chat.

    If useConnectionNamespace is false, it will work as it is right now.

    opened by focux 30
  • Proxy is not defined - IE 11

    Proxy is not defined - IE 11

    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.

    opened by drozdzynski 18
  • Latest version breaks library

    Latest version breaks library

    Describe the bug When using the latest version I get the following error: TypeError: o.sockets.subscribe is not a function

    This is caused when I try to run this.sockets.subscribe('name', ...)

    Expected behavior The app is supposed to access the sockets via this.sockets. as it did in previous version

    Desktop (please complete the following information):

    • OS: Linux
    • Browser Chrome, Firefox

    Additional context Reverting to previous version 3.0.7 solved the issue.

    I could not pinpoint the issue in source code due to ... minimization?

    opened by mikemissing 15
  • Emit socket event from vuex store

    Emit socket event from vuex store

    Hi again, can you give an example how to emit an event from a vuex store action

    opened by ivoribeiro 13
  • Vue-Socket.io sockets function no perform

    Vue-Socket.io sockets function no perform

    @vue/cli 4.2.3 Vue-Socket.io 3.0.9

    I use vue-socket.io 3.0.9 sockets is not normal,use 3.0.7 is ok,why?

    opened by gufyapk 13
  • Uncaught TypeError: Cannot call a class as a function

    Uncaught TypeError: Cannot call a class as a function

    Describe the bug Happens on loading before completely mounting the Vue plugin.

    Desktop (please complete the following information):

    • OS: macOS
    • Browser: Chrome
    • Version: 3.0.4

    Additional context

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import store from './store/index'
    import VueSocketIO from 'vue-socket.io';
    
    import io from 'socket.io-client';
    
    
    
    Vue.config.productionTip = false;
    
    // first, retrieve from any settings provided by the frame
    let hash = window.location.hash;
    let setting_string = hash.split('?');
    let settings = getUriSettings(setting_string[1]);
    console.log(settings);
    
    const connection = io.connect('http://localhost:3000', { transports: ['websocket'], upgrade: false});
    
    Vue.use(VueSocketIO, new VueSocketIO({connection, debug:true}));
    console.log('Initializing Vue');
    new Vue({
        router,
        store,
        sockets: {
            connect: function () {
                console.log('Connected. Sending Authentication');
                this.$socket.emit('authentication', {
                    id: settings.token_id,
                    userId: settings.user_id
                });
            },
            authenticated: function () {
                console.log('Authentication Complete');
                this.subscribeChannel();
            }
        },
        methods: {
            subscribeChannel()
            {
                this.$options.sockets.subscirbe(settings.frame_id, (msg) => {
                    // We received data on the channel. We need to double check now what the server is requesting.
                    // We need to first figure out what the server is sending. Check the object.
                    switch (msg.scene) {
                        case 'miniboard':
                            store.commit('miniboard/set', msg.data);
                            break;
                        case 'bracket_rollout':
                            store.commit('bracket_rollout/set', msg.data);
                            break;
                    }
                });
                console.log('Now Listening On Frame: ' + settings.frame_id);
            }
        },
        render: h => h(App)
    }).$mount('#app');
    
    function getUriSettings(uri)
    {
        // after the ?, get the settings.
        let options = uri.split('&');
        let settings = [];
        // now, let's get the key/value pairs
        options.forEach((key) => {
            let a = key.split('=');
            settings[a[0]] = a[1];
        });
        return settings;
    }
    

    Stack trace provided by debugger:

    Uncaught TypeError: Cannot call a class as a function
        at eval (vue-socketio.js?5132:10)
        at t (vue-socketio.js?5132:10)
        at Function.Vue.use (vue.runtime.esm.js?2b0e:4749)
        at eval (main.js?56d7:21)
        at Module../src/main.js (app.js:2768)
        at __webpack_require__ (app.js:768)
        at fn (app.js:131)
        at Object.0 (app.js:2853)
        at __webpack_require__ (app.js:768)
        at app.js:904
    
    opened by BossOfGames 12
  • Adds basic Vue 3 compatibility

    Adds basic Vue 3 compatibility

    This pull request adds Vue 3 compatibility which should fix #284.

    Previously this fix was open as #287 but seems like it was maybe prematurely closed. I tested my changes out and they appear to work on both Vue 3 and Vue 2.

    As a warning though, my vue 3 tests have not been super thorough because my application is having vue 3 problems with unrelated dependencies. This PR gets past the initial issue, but there may still be deeper problems to debug.

    in progress 
    opened by veryeasily 10
  • Vuex integration: custom callbacks receive data as array

    Vuex integration: custom callbacks receive data as array

    I want to use Vuex integration. I've noticed that Observer.onEvent() function passes data (payload, 2nd arg) as array to passToStore funtion: if(this.store) this.passToStore('SOCKET_'+packet.data[0], [ ...packet.data.slice(1)])

    Few lines below where some socketio events are iterated data is passed without wrapping into array. Socketio events that are iterated: ["connect", "error", "disconnect", "reconnect", "reconnect_attempt", "reconnecting", "reconnect_error", "reconnect_failed", "connect_error", "connect_timeout", "connecting", "ping", "pong"]. Inside loop: if(_this.store) _this.passToStore('SOCKET_'+value, data)

    opened by okas 9
  • Vuex integration: actions are not being called

    Vuex integration: actions are not being called

    I used the Vuex integration in many other projects and works just fine. Now i'm starting a new project and trying to use it, but the actions are never called. The "SOCKET_" prefix in the mutations works fine but the "socket_" prefix used in actions doesn't work.

    export default new Vuex.Store({ state: { connect: false, message: null }, mutations:{ SOCKET_CONNECT: (state, status ) => { //work fine... }, SOCKET_USER_MESSAGE: (state, message) => { console.log('mutation called'); } }, actions: { otherAction: (context, type) => { return true; }, socket_userMessage: (context, message) => { //this actions are never called console.log('action called'); } } })

    opened by Conson1 9
  • Can I use with Vue 3?

    Can I use with Vue 3?

    Hello!

    I have a problem. How can I use with Vue 3? Is support it?

    opened by vadimmarkov 9
  • Allow to use socket.io-client version 3 and 4

    Allow to use socket.io-client version 3 and 4

    feature 
    opened by pulzarraider 0
  • Do you know any v3 or higher server?

    Do you know any v3 or higher server?

    Hello sir, I am an jr.Android Developer and created a socket.io client side with java. So I think you know there is v1 or v2 in client side for java. My problem is that my company use v3 in server side so I have to use v2 client (highest version in java) but I cant connect to their server. So I need to a v3 or higher server side url for test my client side for check the problem is in my side or in server side. Do you know any v3 or higher server?

    Note: When I switch to v1 in client I can easly connect to other v2 servers.

    opened by ErsinDemirbas 0
  • How to connect multiple sockets in a single vuejs project?

    How to connect multiple sockets in a single vuejs project?

    import VueSocketIOExt from 'vue-socket.io-extended'; import { io } from 'socket.io-client';

    const socket = io('http://localhost:3200/'); const socket1 = io('http://localhost:3100/');

    Vue.use(VueSocketIOExt, socket); Vue.use(VueSocketIOExt, socket1);

    I tried using the above code. But only only socket is working. Is it possible to connect both the sockets simultaneously. Thanks for the help in advance

    opened by allenshaji 2
  • Using Store Module

    Using Store Module

    Is it possible to define actions for socket listeners in namespaced modules? How the naming rule would be? Since we need to add module name on dispatch for namespaced module (e.g "moduleName/actionName"), does the backend team need to know about that added module name prefix?

    opened by aliftaufik 0
  • Vuex mode event name strict matching mechanism removed, add Chinese document

    Vuex mode event name strict matching mechanism removed, add Chinese document

    Vuex mode event name strict matching mechanism removed, add Chinese document

    opened by hsbtr 0
  • feat(): vue3 support

    feat(): vue3 support

    opened by Pat1enceLos 1
  • [FIX] Mixin.js for vue 3

    [FIX] Mixin.js for vue 3

    Remove warning message on Vue 3 by renaming beforeDestroy to beforeUnmount. Update readme installation for Vue 3 #304

    opened by Hashs7 0
  • Vue3 composition API documentation

    Vue3 composition API documentation

    It would be great to add documentation on how implement Vue-Socket.io with VueJS 3 composition API.

    opened by djcaesar9114 0
  • Update socket-io-client to latest version

    Update socket-io-client to latest version

    opened by anhhao19xx 0
  • Uncaught Error: Unsupported connection type

    Uncaught Error: Unsupported connection type

    Uncaught Error: Unsupported connection type at t.value (vue-socketio.js?5132:10) at new t (vue-socketio.js?5132:10) at eval (main.js?c6f4:35) at Module../src/pages/Home/main.js (index.js:1818) at webpack_require (index.js:849) at fn (index.js:151) at Object.2 (index.js:1855) at webpack_require (index.js:849) at checkDeferredModules (index.js:46) at index.js:925

    image

    im doing a proyect in my personal computer working ok also works fine in the server but when my colleague try to tun the same code get this error,

    the web page are conected to the socket server in the cloud

    opened by lukaneco 0
Releases(3.0.10)
Owner
Metin Seylan
@google Developer Expert - Cloud, Microservices
Metin Seylan
😻 Socket.io implementation for Vuejs and Vuex

Vue-Socket.io is a socket.io integration for Vuejs, easy to use, supporting Vuex and component level socket consumer managements Demo Chat Application

Metin Seylan 3.6k Jul 23, 2021
native websocket with vuex integration

vue-native-websocket · native websocket implementation for Vuejs 2 and Vuex Install yarn add vue-native-websocket # or npm install vue-native-websoc

Nathan 848 Jul 21, 2021
Admin UI for Socket.IO

Admin UI for Socket.IO

Socket.IO 72 Jul 24, 2021
Vue socket cluster wrapper

Socket cluster implementation for Vuejs 2 leveraging uws Socket cluster documentation Install npm install vue-socket-cluster --save Usage Configuratio

Nigel Tiany 15 Jul 25, 2021
Simple websocket (socket.io) plugin for Vue.js

vue-websocket A socket.io plugin for Vue.js. This package does not support native websockets. At the time, we recommend using vue-native-websocket or

Icebob 524 Jul 21, 2021
A template combining TypeORM, Express, Socket.io, and NuxtJS with a custom server setup using ts-node. Includes a lot of features to help bootstrap and supercharge your application.

expressive-nuxt Features 99% TypeScript and uses ts-node <3 Database management with TypeORM API with ExpressJS User authenication and sessions Email

Micheal Pearce 23 Jul 19, 2021
Vue integration for the Laravel Echo library.

vue-echo Vue 2 integration for the Laravel Echo library. This Vue plugin injects a Laravel Echo instance into all of your vue instances, allowing for

Kerstens Maxim 231 Apr 8, 2021