① 安装SignalR:

npm install @microsoft/signalr 

②在需要用到的界面中引入:

const signalR = require("@microsoft/signalr");

import * as signalR from "@microsoft/signalr");

③在created中创建连接并注册供后端调用的方法,在methods中定义该方法:

data() {
    return {
      connection: null,
      msgs: [],
      dataInfo: { status1: "off", status2: "off" }
    };
  },
created() {
    // 建立连接
    this.connection = new signalR.HubConnectionBuilder()
      .withUrl("http://127.0.0.1:9090/myhub") // 此处填服务器地址
      .withAutomaticReconnect()  // 断开自动重连
      .build();

    // 注册方法(给后端调用的,需要在methods中定义)
    this.connection.on("showmsg", this.ShowMsg);
    this.connection.on("updatedata", this.UpdateData);

    // 开始连接
    this.connection
      .start()
      .then((res) => console.log("Connected!"))
      .catch((err) => {
        console.log(err);
      });
  },

 methods: {
    ShowMsg(msgInfo) {
      this.msgs.push(msgInfo);
    },
    UpdateData(dataMsg) {
      this.dataInfo = dataMsg;
    },
    // 调用后端方法(直接调用invoke注入,需要和后端对接方法名及参数)
    receiveMessage() {
      let params = "Hello";
      this.connection
        .invoke("TestMsg", params)  // invoke(方法名, 参数)
        .then(() => console.log("send succeed!"));
    },
  },

示例:

<template>
  <div id="app">
    <p>展示信息(dataInfo):</p>
    <h3>{{dataInfo}}</h3>

    <p>接到的消息通知(msgs):</p>
    <p v-for="item in msgs">{{ item }}</p>
  </div>
</template>

<script>
// 引入signalr
const signalR = require("@microsoft/signalr");

export default {
  data() {
    return {
      connection: null,
      msgs: [],
      dataInfo: " 
    };
  },

  created() {
    // 建立连接
    this.connection = new signalR.HubConnectionBuilder()
      .withUrl("http://127.0.0.1:9090/myhub")
      .withAutomaticReconnect()
      .build();

    // 注册方法
    this.connection.on("showmsg", this.ShowMsg);
    this.connection.on("updatedata", this.UpdateData);

    // 开始连接
    this.connection
      .start()
      .then((res) => console.log("Connected!"))
      .catch((err) => {
        console.log(err);
      });
  },

  methods: {
    ShowMsg(msgInfo) {
      this.msgs.push(msgInfo);
    },

    UpdateData(dataMsg) {
      this.dataInfo = dataMsg;
    },

    // 调用后端方法
    receiveMessage() {
      let params = "Hello";
      this.connection
        .invoke("TestMsg", params)
        .then(() => console.log("send succeed!"));
    },
  },
};
</script>

<style>
</style>

Logo

前往低代码交流专区

更多推荐