12345678910111213141516171819202122232425262728 |
- import Vue from 'vue'
- let socket = null;
- const eventBus = new Vue(); // 使用一个小型事件总线通知页面
- export function connectWebSocket() {
- const url = '你的WebSocket地址'; // 替换为你的后端地址
- socket = uni.connectSocket({
- url: url,
- success: () => console.log('连接建立成功')
- });
- socket.onMessage(res => {
- const data = JSON.parse(res.data); // 假设返回的是 JSON 格式数据
- if (data.type === 'completed') {
- eventBus.$emit('websocket-message', data);
- }
- });
- socket.onError(err => {
- console.error('WebSocket错误:', err);
- });
- socket.onClose(() => {
- console.log('WebSocket已关闭');
- });
- }
- export { eventBus };
|