参考
1、安装
yarn add stompjs
2、引入
import Stomp from "stompjs";
3、使用
<template>
<!--通过点击消息图标来触发事件-->
<img src="message.png" alt="" @click="openMessage" />
</template>
<script>
import Stomp from "stompjs";
export default {
data() {
return {
client: undefined
}
},
mounted() {
this.connect()
},
methods: {
openMessage() {
NoticeCount().then(res => {
if (res.success) {
this.num = res.data;
}
});
},
connect() {
const url = process.env.VUE_APP_URL;
this.client = Stomp.client(url);
const headers = {
login: "admin",
passcode: "admin",
host: "/",
"heart-beat": "0,0"
};
this.client.connect(headers, this.onConnected, this.onFailed);
},
onConnected() {
const id = window.localStorage.id;
const exchange = `/long/connection/${id}`;
this.client.subscribe(exchange, this.responseCallback, this.onFailed);
},
onFailed() {
setTimeout(() => {
this.connect();
}, 5000);
},
responseCallback() {
NoticeCount().then(res => {
if (res.success) {
this.num = res.data;
}
});
},
disconnect() {
if (this.client != null) {
this.client.disconnect();
}
},
},
destroyed() {
this.disconnect();
}
}
</script>