test.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <template>
  2. <div class="home">
  3. <h1>前端演示SignalR</h1>
  4. <input v-model="user" type="text" />
  5. <input v-model="message" type="text" />
  6. <button @click="sendAll">发送全部</button>
  7. <button @click="sendOwn">对自己发送</button>
  8. <div>
  9. <ul v-for="(item ,index) in messages" v-bind:key="index +'itemMessage'">
  10. <li>{{item.user}} says {{item.message}}</li>
  11. </ul>
  12. </div>
  13. </div>
  14. </template>
  15. <script>
  16. import * as signalR from "@aspnet/signalr";
  17. export default {
  18. name: "SignalR",
  19. components: {},
  20. data() {
  21. return {
  22. token:"",
  23. user: "", //用户
  24. message: "", //消息
  25. connection: "", //signalr连接
  26. messages: [] //返回消息
  27. };
  28. },
  29. methods: {
  30. //给全部发送消息
  31. sendAll: function() {
  32. this.connection
  33. .invoke("SendMessage", this.user, this.message)
  34. .catch(function(err) {
  35. return console.error(err);
  36. });
  37. },
  38. //只给自己发送消息
  39. sendOwn: function() {
  40. this.connection
  41. .invoke("SendMessageCaller", this.message)
  42. .catch(function(err) {
  43. return console.error(err);
  44. });
  45. }
  46. },
  47. created: function() {
  48. this.token = JSON.parse(localStorage.getItem('userinif')).token;
  49. let thisVue = this;
  50. console.log(thisVue.token)
  51. this.connection = new signalR.HubConnectionBuilder()
  52. // .withAutomaticReconnect()//断线自动重连
  53. .withUrl("http://132.232.92.186:8888/chatHub", {
  54. skipNegotiation: true,
  55. transport: signalR.HttpTransportType.WebSockets,
  56. accessTokenFactory: () => thisVue.token
  57. })
  58. .configureLogging(signalR.LogLevel.Information)
  59. .build();
  60. this.connection.on("SendAll", function(data) {
  61. //thisVue.messages.push({ userid, message });
  62. console.log(data);
  63. });
  64. this.connection.on("SendCustomUserMessage", function(userid,message) {
  65. let user = "自己";//这里为了push不报错,我就弄了一个默认值。
  66. thisVue.messages.push({ userid, message });
  67. console.log({ userid, message });
  68. });
  69. this.connection.start();
  70. }
  71. };
  72. </script>