@hlf01/vue3-socket.io

Socket.io implementation for Vue.js 3.0
13,353 2
Install
npm install @hlf01/vue3-socket.io
Latest Version:1.1.1
Vue:3
License:MIT
Last Updated:Jun 27, 2024
Links: GitHub  ·  npm
Maintainer: hlf01

Description

Installation

npm install @hlf01/vue3-socket.io

Example

Register

Using Connection String
import { createApp } from 'vue'
import App from '@/App.vue'
import Vue3SocketIO from '@hlf01/vue3-socket.io';

const vue3SocketIO = new Vue3SocketIO({
    debug: true,
    connection: 'https://example.com',
    options: { path: "/my-app/" } //Optional options
});

const app = createApp(App)

app.use(vue3SocketIO)

app.mount('#app')
Using socket.io-client Instance
import { createApp } from 'vue'
import App from '@/App.vue'
import SocketIO from 'socket.io-client';
import Vue3SocketIO from '@hlf01/vue3-socket.io';

const options = { path: "/my-app/" };
const vue3SocketIO = new Vue3SocketIO({
    debug: true,
    connection: SocketIO('https://example.com', options),
});

const app = createApp(App)

app.use(vue3SocketIO)

app.mount('#app')

Usage

<script setup>
import { onMounted, inject } from "vue";
import { useSocketIO } from "@hlf01/vue3-socket.io";

const socketIO = useSocketIO();
const socket = inject("socket");

onMounted(() => {
    socketIO.subscribe("connect", () => {
        console.log("Socket connected:", socket.id);
    });

    // Custom event name
    socketIO.subscribe("getMessages", (messages) => {
        console.log("Received messages:", messages);
    });
});

// All event listeners will be unsubscribed automatically once the component is unmounted

function unsubscribeEvent(eventName) {
    // Unsubscribe event for current instance
    socketIO.unsubscribe(eventName);
}

function removeEvent(eventName) {
    // Unsubscribe event for all instance
    socketIO.removeEvent(eventName);
}

function sendMessage(message) {
    // Emit event
    socket.emit("sendMessage", message);
}
</script>

Parameters

Parameters Types Default Required Description
connection String/Socket null Required Websocket server url or socket.io-client instance.
debug Boolean false Optional Enable logging for debug.
options Partial<ManagerOptions & SocketOptions> null Optional Socket.io options for connection and configuration. See socket.io-client options documentation for more information.

Related Packages

vue-socket.io

socket.io implementation for Vue.js and Vuex

474,562 3,890
vue-3-socket.io

socket.io implementation for Vue.js and Vuex

49,565 42
vue-socket.io-extended

Socket.io bindings for Vue.js and Vuex (inspired by Vue-Socket.io)

207,114 625
vue-websocket

Websocket handler for Vue.js

12,473 522

Version History

Version Released License
1.1.1 MIT
1.1.0 MIT
1.0.2 MIT
1.0.1 MIT
1.0.0 MIT