@dreamonkey/vue-signalr

中文文档
1.2.0发布于 2024/09/11MITTypeScriptCommonJS零依赖近 30 天下载 1.4万

SignalR plugin for Vue 3

原始使用文档
文档目录7 节
  1. Installation
  2. Usage
  3. Type-safety
  4. Methods remapping
  5. Error Handling
  6. Possible next steps
  7. Credits

vue-signalr

A Vue3 plugin which wraps SignalR and provider stricter typings.

Installation

Install this package and SignalR peer dependency

$ yarn add @dreamonkey/vue-signalr @microsoft/signalr

Apply the plugin providing a HubConnection instance

import { VueSignalR } from "@dreamonkey/vue-signalr";
import { HubConnectionBuilder } from "@microsoft/signalr";
import { createApp } from "vue";
import App from "./App.vue";

// Create your connection
// See https://docs.microsoft.com/en-us/javascript/api/@microsoft/signalr/hubconnectionbuilder
const connection = new HubConnectionBuilder()
  .withUrl("http://localhost:5000/signalr")
  .build();

createApp(App).use(VueSignalR, { connection }).mount("#app");

Usage

import { useSignalR } from "@dreamonkey/vue-signalr";
import { inject } from "vue";

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

    signalr.invoke("SendMessage", { message });

    signalr.on("MessageReceived", ({ message }) => {
      /* do stuff */
    });
  },
};

While SignalR doesn't make a distinction between client side and server side methods, into this package we refer the formers as "Events" and the latters as "Commands".

Commands can be sent using signalr.invoke(), while events can be enabled or disabled using signalr.on() and signalr.off()

Unsubscribing

All Event you create a listener for using signalr.on() must be unsubscribed when not used anymore, to avoid memory leaks and erratic code behavior. If you call signalr.on() within a Vue component setup scope, the listener will be unsubscribed automatically into onBeforeUnmount hook. This behavior can be disabled via autoOffInsideComponentScope plugin option.

If you disabled it, or you start a listener outside a component scope, you'll need to unsubscribe it manually using signal.off() and providing the same listener function reference to it. Not providing it will remove all listeners from the provided Event

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

signalr.on("MessageReceived", messageReceivedCallback);

signalr.off("MessageReceived", messageReceivedCallback); // Remove this listener
signalr.off("MessageReceived"); // Remove all listeners on `MessageReceived` event

Type-safety

Command and Events names and payloads are registered via type augmentation of dedicated interfaces (SignalREvents and SignalRCommands) into @dreamonkey/vue-signalr scope. These types are later used to provide you autocompletion.

The package works with plain strings too, you're not required to register Commands/Events typings

import "@dreamonkey/vue-signalr";

interface MessageReceivedPayload {
  message: string;
}

interface SendMessagePayload {
  message: string;
}

declare module "@dreamonkey/vue-signalr" {
  interface SignalREvents {
    // Define an event, its payload is a single parameter of type `MessageReceivedPayload`
    MessageReceived: MessageReceivedPayload;
    // Define an event, its payload is composed by 0 or more parameters of type `MessageReceivedPayload`
    MultipleMessagesReceived: MessageReceivedPayload[];
    // Define an event, its payload is composed by exactly 2 parameters of type `MessageReceivedPayload`
    TwoMessagesReceived: [MessageReceivedPayload, MessageReceivedPayload];
    // Define an event with no payload
    MainTopicJoined: false;
  }

  interface SignalRCommands {
    // Define a command and its payload
    SendMessage: SendMessagePayload;
    // Define a command with no payload
    JoinMainTopic: false;
  }
}

Methods remapping

In case you need to remap a Command or Event name, you could do so using remapMethod or remapMethods helpers

import { remapMethod } from "@dreamonkey/vue-signalr";

remapMethod("receiveMessageWithStrangeMethodName", "MessageReceived");

remapMethods([
  ["legacyTopic2Joined", "MainTopicJoined"],
  ["createNewMessage", "SendMessage"],
]);

Error Handling

You can react to connection/reconnection errors providing a failFn option into the plugin options

import { VueSignalR } from "@dreamonkey/vue-signalr";
import { createApp } from "vue";
import App from "./App.vue";

const connection = new HubConnectionBuilder()
  .withUrl("http://localhost:5000/signalr")
  .build();

createApp(App)
  .use(VueSignalR, {
    connection,
    failFn: () => {
      /* do stuff */
    },
  })
  .mount("#app");

Possible next steps

Credits

This package has been inspired by https://github.com/quangdaon/vue-signalr

版本与发布记录

@dreamonkey/vue-signalr 共发布 7 个版本,首次发布于 2021/07/16;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.2.0latest2024/09/112 年前
1.1.02023/04/033 年前
1.0.12022/01/114 年前
1.0.02022/01/114 年前
0.0.32021/08/235 年前
0.0.22021/08/235 年前

关于 @dreamonkey/vue-signalr 的常见问题

@dreamonkey/vue-signalr 是什么?

SignalR plugin for Vue 3

如何安装 @dreamonkey/vue-signalr?

在项目目录运行 npm install @dreamonkey/vue-signalr,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:vue(^3.0.0)、@microsoft/signalr(^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@dreamonkey/vue-signalr 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@dreamonkey/vue-signalr 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@dreamonkey/vue-signalr 可以商用吗?

@dreamonkey/vue-signalr 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@dreamonkey/vue-signalr 的下载量有多少?

根据 npm 官方下载统计,@dreamonkey/vue-signalr 在 2026/10/13 – 2026/11/11 这 30 天内被下载 13,695 次,日均约 457 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@dreamonkey/vue-signalr 还在维护吗?

最新版本 1.2.0 发布于 2024/09/11(2 年前);至今共发布 7 个版本,其中过去 12 个月发布了 0 个;首次发布于 2021/07/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。