当前位置: 首页 > 工具软件 > stomp.js > 使用案例 >

Vue+websocket+stompjs实现长连接(用于实时接收消息)

微生高谊
2023-12-01

参考

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() {
				//VUE_APP_URL="wss://abcd.net/ws";   //后端提供
				const url = process.env.VUE_APP_URL;
				this.client = Stomp.client(url);
				const headers = {
					login: "admin",
					passcode: "admin",
					host: "/",
					"heart-beat": "0,0"
				};
				//client.connect(login, passcode, connectCallback, errorCallback, host);
				this.client.connect(headers, this.onConnected, this.onFailed);
			},
			onConnected() {
				const id = window.localStorage.id;
				const exchange = `/long/connection/${id}`;//后端提供
				//目的地(destination),回调函数(callback);还有一个可选的参数headers
				//client.subscribe(destination, successCallback, errorCallback);
				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>
 类似资料: