123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <template>
- <div class="home">
- <h1>前端演示SignalR</h1>
- <input v-model="user" type="text" />
- <input v-model="message" type="text" />
- <button @click="sendAll">发送全部</button>
- <button @click="sendOwn">对自己发送</button>
- <div>
- <ul v-for="(item ,index) in messages" v-bind:key="index +'itemMessage'">
- <li>{{item.user}} says {{item.message}}</li>
- </ul>
- </div>
- </div>
- </template>
-
- <script>
- import * as signalR from "@aspnet/signalr";
- export default {
- name: "SignalR",
- components: {},
- data() {
- return {
- token:"",
- user: "", //用户
- message: "", //消息
- connection: "", //signalr连接
- messages: [] //返回消息
- };
- },
- methods: {
- //给全部发送消息
- sendAll: function() {
- this.connection
- .invoke("SendMessage", this.user, this.message)
- .catch(function(err) {
- return console.error(err);
- });
- },
- //只给自己发送消息
- sendOwn: function() {
- this.connection
- .invoke("SendMessageCaller", this.message)
- .catch(function(err) {
- return console.error(err);
- });
- }
-
-
- },
- created: function() {
- this.token = JSON.parse(localStorage.getItem('userinif')).token;
- let thisVue = this;
- console.log(thisVue.token)
- this.connection = new signalR.HubConnectionBuilder()
- // .withAutomaticReconnect()//断线自动重连
- .withUrl("http://132.232.92.186:8888/chatHub", {
- skipNegotiation: true,
- transport: signalR.HttpTransportType.WebSockets,
- accessTokenFactory: () => thisVue.token
- })
- .configureLogging(signalR.LogLevel.Information)
- .build();
- this.connection.on("SendAll", function(data) {
- //thisVue.messages.push({ userid, message });
- console.log(data);
- });
- this.connection.on("SendCustomUserMessage", function(userid,message) {
- let user = "自己";//这里为了push不报错,我就弄了一个默认值。
- thisVue.messages.push({ userid, message });
- console.log({ userid, message });
- });
- this.connection.start();
- }
- };
- </script>
|