VUE2 + WebSocket + element Notification

VUE2 + WebSocket + element Notification

1.创建socket.global.js

/**
 * 全局websocket
 */
export default {
	WebSocket: {},
	socketUrl: "192.168.1.xxx:8080/ws",
	type: "pc",
	setWebSocket: function(socketContent) {
		this.WebSocket = socketContent;
	}
}

2.main.js 引入socket

import socketGlobal from '/src/socket/socket.global.js'
// 全局socket
Vue.prototype.socketGlobal = socketGlobal;

3.socket方法逻辑,记得自己定义notifications参数

		    /**
			 * webSocket 连接
			 */
			connectSocket() {
				const userToken = getToken("pcToken");
				if (!userToken) return;
				let that = this;
				// 连接状态
				let connected = false;
				// 是否正在连接
				let connecting = true;
				let messageIdData = [];
				if (!("WebSocket" in window)) {
					return console.log("浏览器不支持socket");
				}
				const locationUrl = window.location.href;
				const connectionPrefix = locationUrl.includes("https") ? "wss" : "ws";
				const msg = JSON.stringify({
					"type": that.socketGlobal.type,
					"token": userToken
				});
				that.webSocket = new WebSocket(connectionPrefix + "://" + that.socketGlobal.socketUrl + msg);
				that.socketGlobal.setWebSocket(that.webSocket);
				/**
				 * 再次发送消息
				 */
				const onceMoreSend = (time = 10000) => {
					// 无消息,每隔10秒监听一次
					setTimeout(() => {
						console.log("socket 发送消息", msg);
						that.webSocket.send(msg);
					}, time);
				}

				/**
				 * 连接成功
				 */
				that.webSocket.onopen = function() {
					connected = true;
					connecting = false;
					that.webSocket.send(msg);
				};

				/**
				 * 接收消息
				 * @param {Object} event
				 */
				that.webSocket.onmessage = async (event) => {
					const onMsgData = JSON.parse(event.data);
					// 连接完成了,再开始
					if (connected && !connecting) {
						// 有消息并且是有数据返回的
						if (onMsgData && onMsgData.status) {
							const notifyList = onMsgData.data;
							// 有数据才渲染(再次确实是否有数据)
							if (notifyList && notifyList.length) {
								let notifyRecord = {},
									messageId = 0,
									messageLink = "";
								// 开始发送消息
								let senMsgPromise = new Promise((resolve, reject) => {
									for (let notifyIndex = 0; notifyIndex < notifyList
										.length; notifyIndex++) {
										setTimeout(() => {
											const notifyItem = notifyList[notifyIndex];
											// 是否是最后一条信息
											const lastMsg = notifyIndex + 1 == notifyList.length;
											// 已经渲染了就跳出
											if (that.notifications[notifyItem.messageId]) {
												if (lastMsg) {
													resolve(true);
												}
											} else {
												// 开始处理逻辑
												notifyRecord.duration = 0;
												notifyRecord.title = notifyItem.title;
												notifyRecord.message = notifyItem.msg;
												notifyRecord.iconClass = "notify-record__icon";
												// 用户已读后,给服务端发消息
												notifyRecord.onClick = () => {
													that.closeNotification(true, notifyItem
														.messageId, notifyItem.link);
												};
												notifyRecord.onClose = () => {
													that.closeNotification(false,
														notifyItem
														.messageId);
												};
												let notifyInfo = that.$notify.info(
													notifyRecord);
												that.notifications[notifyItem.messageId] =
													notifyInfo;
												if (lastMsg) {
													resolve(true);
												}
											}
										}, 1000);
									};
								});
								// 已渲染完成,重新发送消息
								Promise.all([senMsgPromise]).then((result) => {
									if (result[0] === true) {
										onceMoreSend();
									}
								});
							} else {
								// 数据不对,重新请求
								onceMoreSend();
							}
						} else {
							// 无消息,每隔10秒监听一次
							onceMoreSend();
						}
					}
				};

				/**
				 * 关闭消息
				 */
				that.webSocket.onclose = function() {
					connected = false;
					console.log("连接已关闭...");
					//断线重新连接
					setTimeout(() => {
						connecting = true;
						that.connectSocket();
					}, 10000);
				};
			},
			/**
			 * 关闭通知
			 * @param {Object} messageId
			 */
			closeNotification(jump, messageId, link) {
				if (!messageId) return console.log("无消息ID");
				// 无跳转就直接关闭
				if (jump && !link) return this.notifications[messageId].close();
				// 清除该消息并设置为已读
				if (!this.notifications[messageId]) return console.log("无消息ID~");
				// 走接口清除消息
				delete this.notifications[messageId];
				// 如果需要跳转
				if (jump && link) {
					return window.open(link);
				}
			}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值