vue 中使用 websocket
2020-10-10 本文已影响0人
Hi丶粢醍
image.png
<script>
// 引用API接口
import SockJS, { log } from "../../../public/js/sockjs";
import "../../../public/js/stomp";
// 样式/* */
export default {
name: "",
created() {
getHallNow().then((res) => {
this.loadShow = true;
this.today_all = res.today_all;
const queues = res.queues;
Object.keys(queues).forEach((key, index) => {
// 需修改
this.queue.push(queues[index]);
this.waitNum += queues[key].nCount;
queues[index].nCount >= 1 ? this.hasCount++ : "";
});
this.hasCountChange();
});
this.connect();
window.onunload = function () {
disconnect();
};
},
methods: {
// webSocket
connect() {
let stompClient = null;
let socket = new SockJS("http://******/"); //网络请求地址
stompClient = Stomp.over(socket); //使用STMOP子协议的WebSocket客户端
stompClient.connect({}, (frame) => {
console.log("Connected:" + frame);
stompClient.subscribe("/topic/getResponse", (response) => {
const getRes = JSON.parse(response.body);
if (getRes.today_all !== undefined) {
this.today_all = getRes.today_all;
}
this.waitNum = 0;
// 取号获取有值的条数数目变量
let tuiSongNum = 0;
Object.keys(this.queue).forEach((key, index) => {
if (this.queue[index].sID == getRes.queueId) {
this.queue[index].nCount = getRes.nWait;
}
this.waitNum += this.queue[key].nCount;
// 取号获取有值的条数数目
this.queue[index].nCount > 0 ? tuiSongNum++ : "";
});
this.hasCount = tuiSongNum;
this.hasCountChange();
});
});
},
disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
},
};
</script>