在 Vue.js 项目中封装一个 WebSocket 工具是一个很好的实践,这样可以让你的代码更加模块化和易于维护。下面是一个基本的示例,展示了如何创建一个简单的 WebSocket 服务封装:

创建 WebSocket 服务

首先,你可以创建一个名为 wsService.js 的文件来封装 WebSocket 逻辑:

// wsService.js
class WebSocketService {
  constructor(url) {
    this.socket = null;
    this.url = url;
    this.callbacks = {};
    this.connect();
  }

  connect() {
    if (!this.socket || this.socket.readyState === WebSocket.CLOSED) {
      this.socket = new WebSocket(this.url);
      this.initEventHandlers();
    }
  }

  initEventHandlers() {
    this.socket.onopen = () => {
      console.log('WebSocket连接已打开');
    };

    this.socket.onmessage = (event) => {
      const message = JSON.parse(event.data);
      this.handleMessage(message);
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket发生错误', error);
    };

    this.socket.onclose = () => {
      console.log('WebSocket连接已关闭');
      // 可根据需要自动重连
      setTimeout(() => this.connect(), 5000);
    };
  }

  handleMessage(message) {
    const { type, data } = message;
    if (this.callbacks[type]) {
      this.callbacks[type].forEach(callback => callback(data));
    }
  }

  subscribe(type, callback) {
    if (!this.callbacks[type]) {
      this.callbacks[type] = [];
    }
    this.callbacks[type].push(callback);
  }

  unsubscribe(type, callback) {
    if (this.callbacks[type]) {
      this.callbacks[type] = this.callbacks[type].filter(cb => cb !== callback);
    }
  }

  send(message) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message));
    } else {
      console.error('WebSocket连接未打开,无法发送消息');
    }
  }

  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}

export default WebSocketService;

在 Vue 组件中使用

然后,在你的 Vue 组件中引入并使用这个服务:

// YourComponent.vue
<template>
  <!-- Your component template -->
</template>

<script>
import WebSocketService from './wsService';

export default {
  name: 'YourComponent',
  data() {
    return {
      wsService: null,
    };
  },
  mounted() {
    this.initWebSocket();
  },
  beforeDestroy() {
    this.wsService.close();
  },
  methods: {
    initWebSocket() {
      this.wsService = new WebSocketService('ws://your-websocket-url');
      this.wsService.subscribe('messageType', this.handleMessage);
    },
    handleMessage(data) {
      console.log('Received:', data);
      // 处理接收到的数据
    },
    sendMessage(message) {
      this.wsService.send({ type: 'yourMessageType', data: message });
    },
  },
};
</script>

在这个例子中,我们创建了一个 WebSocketService 类来管理 WebSocket 连接、消息订阅/取消订阅、发送消息和关闭连接等操作。在 Vue 组件中,我们初始化这个服务并在组件生命周期的适当阶段(如 mountedbeforeDestroy)管理它的连接状态。这样,你就可以在任何需要使用 WebSocket 功能的组件中轻松复用这个服务了。

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐