Skip to content

03. Usage

Quangdao Nguyen edited this page Dec 20, 2021 · 2 revisions

This plugin provides a composable function to inject the SignalR service:

import { inject } from 'vue';
import { useSignalR } from '@quangdao/vue-signalr';

export default {
  setup() {
    const signalr = useSignalR();
  }
};

Tokens

For type safety, I recommend declaring constant tokens. As an example:

import { MyObject } from '@/models/my-object';
import { HubCommandToken, HubEventToken } from '@quangdao/vue-signalr';

export const SendMessage: HubCommandToken<MyObject> = 'SendMessage';
export const MessageReceived: HubEventToken<MyObject> = 'MessageReceived';

// models/my-object.ts
export interface MyObject {
  prop: string;
}

Receiving Messages

If you used tokens mentioned above:

setup() {
  signalr.on(MessageReceived, (message) => console.log(message.prop));
}

Alternatively, you can pass in the method name as a string, with an optional type argument for the data:

// Both of these work:
signalr.on('MessageReceived', message => console.log(message.prop)); // Data object is untyped
signalr.on<MyObject>('MessageReceived', message => console.log(message.prop));

Unsubscribing

If automaticUnsubscribe is configured (enabled by default), Vue SignalR will automatically unsubscribe from all events called within a component when the component is destroyed. If you need to programmatically unsubscribe from an event, you can use signalr.off.

Same rules regarding tokens above apply here.

setup() {
  const messageReceivedCallback = (message) => console.log(message.prop);

  signalr.on(MessageReceived, messageReceivedCallback);
  onBeforeUnmount(() => signalr.off(MessageReceived, messageReceivedCallback));
}

Sending Message

To send a message to the server, you can either invoke a command if you are expecting a response, or send a command without waiting for an acknowledgement. Same rules regarding tokens above apply to both methods.

signalr.send(SendMessage, { prop: 'value' });
signalr
  .invoke(SendMessage, { prop: 'value' })
  .then(response => doSomethingWith(response));

Error Handling

Errors can be handled at the app level by passing in a property to the options object. See Configuration#disconnected for more details.

You can also attach an event listener to the connection itself, however, be aware that because this is the global connection object used by the service, the listener will not be unbound when the component is destroyed:

setup() {
  const signalr = useSignalR();
  signalr.connection.onclose(() => customCallback());
}

Alternatively, if you just need a flag to check whether the you are still connected, the service exposes a ref through signalr.getConnectionStatus().