uni-app vue3封装websocket,支持微信小程序

一、创建useWebSocket.js 文件

javascript 复制代码
// useWebSocket.js 

// 获取链接的URL前缀
import {
	BASE_URL
} from "./request";
 
import {
	ref,
	onMounted,
	onBeforeUnmount
} from "vue";

// 假设我们使用 uni-app 的 globalData 或 Vuex 来管理用户状态  
// 这里为了简单起见,我们假设用户ID是直接从某处获取的  

const useWebSocket = (
	url,
	reconnectInterval = 10000,
	maxReconnectAttempts = 5
) => {
	const isMounted = ref(true);
	const isConnected = ref(false);
	const messages = ref([]);
	let reconnectAttempts = 0;

	const connect = () => {
		if (isConnected.value) {
			uni.closeSocket(); // 关闭已有的 WebSocket 连接  
		}

		const uri = `ws://${BASE_URL}/websocket/tender/${url}`;

		// 使用微信小程序的 WebSocket API  
		uni.connectSocket({
			url: uri,
			success: () => {
				console.log("WebSocket连接已打开");
				isConnected.value = true;
				// 监听消息  
				uni.onSocketMessage((res) => {
					messages.value = JSON.parse(res.data);
				});

				// 监听WebSocket的关闭  
				uni.onSocketClose(() => {
					console.log("WebSocket连接已关闭");
					isConnected.value = false;
					if (isMounted.value && reconnectAttempts < maxReconnectAttempts) {
						setTimeout(connect, reconnectInterval * (reconnectAttempts + 1));
						reconnectAttempts++;
					}
				});

				// 监听WebSocket的错误  
				uni.onSocketError((res) => {
					console.error("WebSocket发生错误:", res.errMsg);
					if (isMounted.value) {
						setTimeout(connect, reconnectInterval);
					}
				});
			},
			fail: (err) => {
				console.error("WebSocket连接失败:", err);
			}
		});
	};

	const sendMessage = (message) => {
		if (isConnected.value) {
			uni.sendSocketMessage({
				data: message,
				success: () => {
					console.log('消息发送成功');
				},
				fail: (err) => {
					console.error('发送失败', err);
				}
			});
		}
	};

	onMounted(() => {
		isMounted.value = true;
		connect();
	});

	onBeforeUnmount(() => {
		isMounted.value = false;
		if (isConnected.value) {
			uni.closeSocket();
		}
	});

	return {
		isConnected,
		messages,
		sendMessage
	};
};

export default useWebSocket;

二、在 .vue文件中使用

javascript 复制代码
<script setup>

import {
		onLoad
	} from "@dcloudio/uni-app";

	import {
		ref,
		watchEffect
	} from 'vue';
// 引入useWebSocket
import useWebSocket from "@/api/useWebSocket.js";
onLoad((options) => {
		id.value = options.id
		messages.value = useWebSocket(options.id, 10000, 5);
	})

// 监听messages
watchEffect(() => {
		let timeVal = {
			...messages.value
		};
		console.log(timeVal);
	})

</script>
相关推荐
2501_9159214326 分钟前
前端开发工具有哪些?常用前端开发工具、前端调试工具、前端构建工具与效率提升工具对比与最佳实践
android·前端·ios·小程序·uni-app·iphone·webview
哆啦A梦15885 小时前
[前台小程序] 01 项目初始化
前端·vue.js·uni-app
2501_915918418 小时前
HTTPS 端口号详解 443 端口作用、iOS 抓包方法、常见 HTTPS 抓包工具与网络调试实践
android·网络·ios·小程序·https·uni-app·iphone
小蒜学长10 小时前
基于springboot 校园餐厅预约点餐微信小程序的设计与实现(代码+数据库+LW)
数据库·spring boot·微信小程序
cookqq10 小时前
Cursor和Hbuilder用5分钟开发微信小程序
微信小程序·小程序·curosor
毕设源码-钟学长12 小时前
【开题答辩全过程】以 基于微信小程序的美发服务系统的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
canglingyue13 小时前
微信小程序罗盘功能开发指南
微信小程序·小程序
三脚猫的喵16 小时前
微信小程序中实现AI对话、生成3D图像并使用xr-frame演示
前端·javascript·ai作画·微信小程序
2501_9151063217 小时前
App Store 软件上架全流程详解,iOS 应用发布步骤、uni-app 打包上传与审核要点完整指南
android·ios·小程序·https·uni-app·iphone·webview
快起来搬砖了17 小时前
实现一个优雅的城市选择器组件 - Uniapp实战
开发语言·javascript·uni-app