Socket.io Bindings for Vue.js and Vuex
Vue-Socket.io-Extended is a robust library that provides seamless integration of Socket.io with Vue.js applications, including comprehensive support for Vuex state management. The current stable version is `4.2.0`, which targets Vue 2.x. Development is active for `v5.0.0-alpha` releases, which introduce support for Vue 3.x. The project aims to offer a more stable, tested, and feature-rich alternative to its inspiration, Vue-Socket.io, focusing on aspects like reactive properties for connection status, automatic dispatching of Vuex actions/mutations based on socket events, and strong TypeScript support. Its release cadence shows periodic updates, with significant work being done for the next major Vue 3 compatible version. It differentiates itself with lightweight design, good TypeScript support (including decorators), and flexibility in handling Socket.io client versions.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'emit') or this.$socket is undefined
cause The `vue-socket.io-extended` plugin was not correctly installed via `Vue.use()` or the `socket.io-client` instance was not provided.fixEnsure `Vue.use(VueSocketIOExtended, socketInstance)` is called before creating your Vue app. Also verify `socket.io-client` is installed and `io()` is correctly used to create the `socketInstance`. -
Failed to compile / Module not found: Error: Can't resolve 'socket.io-client'
cause The `socket.io-client` package is a required dependency but is not installed in the project.fixInstall the `socket.io-client` package: `npm install socket.io-client` or `yarn add socket.io-client`. -
Error during WebSocket handshake: Unexpected response code: 400
cause This often indicates a CORS (Cross-Origin Resource Sharing) issue or a mismatch in the Socket.io server configuration (e.g., path, transports).fixOn your Socket.io server, ensure CORS is correctly configured to allow requests from your Vue application's origin. For example, `const io = new Server(server, { cors: { origin: 'http://localhost:8080' } });`. Also, check the connection URL and any `path` options. -
The Socket instance will no longer forward the events emitted by its Manager
cause This is a change in behavior in `socket.io` version 3.x, where the `Socket` instance no longer automatically re-emits events from its underlying `Manager` (e.g., `connect_error`).fixIf you relied on `socket.on('connect_error')` or similar on the `Socket` instance, you might need to explicitly listen on the `Manager` instance (`socket.client.on('connect_error')`) or adapt your error handling strategy.
Warnings
- breaking Version 5.0.0-alpha.1 introduced breaking changes, specifically dropping support for Vue 2.x in favor of Vue 3.x. Projects using Vue 2 must remain on the 4.x branch.
- breaking The `@Socket()` decorator's import path changed in v5.x. It is no longer exported from the root package.
- gotcha When using the `@Socket()` decorator, ensure your build setup supports ECMAScript stage 1 decorators. This typically requires `babel-plugin-transform-decorators-legacy` for Babel or enabling `--experimentalDecorators` in TypeScript.
- gotcha Socket.io server and client versions must be compatible. Major version mismatches (e.g., Socket.io client v3 with server v2) can lead to connection issues.
- gotcha If integrating with Vuex, mutations should be prefixed with `SOCKET_` and actions with `socket_` by default to be automatically dispatched on socket events. This behavior is configurable.
Install
-
npm install vue-socket.io-extended -
yarn add vue-socket.io-extended -
pnpm add vue-socket.io-extended
Imports
- VueSocketIOExtended
const VueSocketIOExtended = require('vue-socket.io-extended');import VueSocketIOExtended from 'vue-socket.io-extended';
- io
import io from 'socket.io-client';
import { io } from 'socket.io-client'; - Socket
import { Socket } from 'vue-socket.io-extended';import Socket from 'vue-socket.io-extended/decorator';
Quickstart
import Vue from 'vue';
import VueSocketIOExtended from 'vue-socket.io-extended';
import { io } from 'socket.io-client';
// Assuming a Socket.io server is running at http://localhost:3000
const socketInstance = io('http://localhost:3000');
// Optional: Import your Vuex store if you're using it
// import store from './store';
Vue.use(VueSocketIOExtended, socketInstance, {
// Pass your Vuex store here if needed
// store: store,
// Optional: Set custom event transformers for Vuex (e.g., to match custom naming conventions)
// actionPrefix: 'SOCKET_', // Default
// mutationPrefix: 'SOCKET_'
});
new Vue({
el: '#app',
data: () => ({ message: 'Waiting for messages...' }),
sockets: {
connect() {
console.log('Socket connected successfully!');
this.message = 'Connected to server!';
},
disconnect() {
console.log('Socket disconnected.');
this.message = 'Disconnected from server.';
},
// Listen for a custom 'chatMessage' event from the server
chatMessage(data: string) {
console.log('Received message:', data);
this.message = `Received: ${data}`;
}
},
methods: {
// Emit a 'sendMessage' event to the server
sendMessage(payload: string) {
if (this.$socket.connected) {
this.$socket.emit('sendMessage', payload);
console.log('Sent message:', payload);
} else {
console.warn('Socket not connected, message not sent.');
}
}
},
mounted() {
this.sendMessage('Hello from Vue.js!');
},
template: `
<div id="app">
<h1>Vue-Socket.io-Extended Example</h1>
<p>{{ message }}</p>
<button @click="sendMessage('Ping from client!')">Send Ping</button>
<p>Connection Status: {{ $socket.connected ? '🟢 Connected' : '🔴 Disconnected' }}</p>
</div>
`
});