test.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <!-- <template>
  2. <div class="hello">
  3. <div id="message" v-html="remsg"></div>
  4. <input type="text" placeholder="请输入用户名" v-model="user" />
  5. <input type="text" placeholder="请输入内容" v-model="msg">
  6. <button @click="handle">发送消息</button>
  7. </div>
  8. </template>
  9. <script>
  10. import * as signalR from "@aspnet/signalr";
  11. let token=JSON.parse(localStorage.getItem('userinif')).token;
  12. let hubUrl = "http://132.232.92.186:8888/chatHub";
  13. //.net core 版本中默认不会自动重连,需手动调用 withAutomaticReconnect
  14. const connection = new signalR.HubConnectionBuilder()
  15. // .withAutomaticReconnect()//断线自动重连
  16. .withUrl(hubUrl,{ accessTokenFactory: () => token })//传递参数Query["access_token"]
  17. .build();
  18. //启动
  19. connection.start().catch(err => {
  20. console.log(err);
  21. });
  22. //自动重连成功后的处理
  23. // connection.onreconnected(connectionId => {
  24. // console.log(connectionId);
  25. // });
  26. export default {
  27. name: "First",
  28. mounted() {
  29. var _this = this;
  30. //调用后端方法 SendMessageResponse 接收定时数据
  31. connection.on("SendMessageResponse", function(data) {
  32. if(data.state==200)
  33. _this.remsg = _this.remsg + "<br>" + "定时数据:" + data.msg;
  34. });
  35. //调用后端方法 SendMessage 接受自己人发送消息
  36. connection.on("SendMessage", function(data) {
  37. if(data.state==200)
  38. _this.remsg = _this.remsg + "<br>" + data.data.userName + ":" + data.msg;
  39. });
  40. //调用后端方法 ConnectResponse 接收连接成功
  41. connection.on("ConnectResponse", function(data) {
  42. if(data.state==200)
  43. _this.remsg = _this.remsg + "<br>" + "连接:" + data.msg;
  44. });
  45. },
  46. data() {
  47. return {
  48. user: "",
  49. msg: "",
  50. remsg: ""
  51. };
  52. },
  53. methods: {
  54. handle: function() {
  55. if(this.msg.trim()==""){
  56. alert("不能发送空白消息");
  57. return;
  58. }
  59. //调用后端方法 SendMessage 传入参数
  60. connection.invoke("SendMessage", this.user, this.msg);
  61. this.msg = "";
  62. }
  63. }
  64. };
  65. </script>
  66. Add "scoped" attribute to limit CSS to this component only -->
  67. <style scoped>
  68. #message {
  69. overflow-y:auto;
  70. text-align: left;
  71. border: #42b983 solid 1px;
  72. height: 500px;
  73. }
  74. </style>