Skip to content

Commit 66bb1a7

Browse files
committed
provide useSocket() function
This can be used in Vue's setup() function to inject the socket instance where $scoket is not available: setup() { const socket = useSocket() }
1 parent df83685 commit 66bb1a7

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

Diff for: src/plugin.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// eslint-disable-next-line import/no-extraneous-dependencies
2-
import { ref } from 'vue';
2+
import { ref, inject } from 'vue';
33
import Observe from './Observe';
44
import GlobalEmitter from './GlobalEmitter';
55
import createMixin from './createMixin';
@@ -53,6 +53,8 @@ function defineSocketIoClient(socket, obj) {
5353
});
5454
}
5555

56+
const SocketExtensionKey = Symbol('$socket');
57+
5658
function install(app, socket, options) {
5759
if (!isSocketIo(socket)) {
5860
throw new Error('[vue-socket.io-ext] you have to pass `socket.io-client` instance to the plugin');
@@ -67,6 +69,11 @@ function install(app, socket, options) {
6769
app.config.optionMergeStrategies.sockets = (toVal, fromVal) => ({ ...toVal, ...fromVal });
6870
Observe(socket, options);
6971
app.mixin(createMixin(GlobalEmitter));
72+
app.provide(SocketExtensionKey, $socket);
7073
}
7174

72-
export { defaults, install };
75+
const useSocket = () => inject(SocketExtensionKey);
76+
77+
export default {
78+
defaults, install, useSocket, SocketExtensionKey,
79+
};

Diff for: types/index.d.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// @ts-ignore
2-
import { PluginInstallFunction } from 'vue';
2+
import { InjectionKey, PluginInstallFunction } from 'vue';
33
import { VueDecorator } from 'vue-class-component';
44
import * as SocketIOClient from 'socket.io-client';
55
// augment typings of Vue.js
@@ -23,3 +23,15 @@ declare class VueSocketIOExt {
2323

2424
export default VueSocketIOExt;
2525
export const Socket: (eventName?: string) => VueDecorator;
26+
27+
export interface SocketExtension {
28+
client: SocketIOClient.Socket;
29+
$subscribe: (event: string, fn: Function) => void;
30+
$unsubscribe: (event: string) => void;
31+
connected: boolean;
32+
disconnected: boolean;
33+
}
34+
35+
export declare const SocketExtensionKey: InjectionKey<SocketExtension>
36+
export declare const useSocket: () => SocketExtension
37+

0 commit comments

Comments
 (0)