vue项目中请求WebSocket获取数据

vue yekong 370℃

vue项目开发中,后端提供的是WebSocket,这里记录一下前端请求ws获取数据的代码实例

这里我们将ws接口地址单独放在一个配置文件中,方便后期修改。

之前的项目开发中是使用之前的ws请求写法

调试输出请求的数据

vue项目中请求WebSocket获取数据

请求实例代码

<script>
import {wsUrl} from '@/api/ipConfig.js';

export default {
  data() {
    return {
      socket: null,
      messages: [],
    }
  },
  mounted() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      // 创建WebSocket连接
      this.socket = new WebSocket(wsUrl + '/ws/socket');

      // 连接打开时触发
      this.socket.onopen = (event) => {
        console.log("WebSocket连接已打开", event);
        // 你可以发送一些数据,例如:
        // this.socket.send("Hello, Server!");
      };

      // 收到服务器消息时触发
      this.socket.onmessage = (event) => {
        console.log("收到服务器消息:", event.data);
        this.messages.push(event.data);
      };

      // 连接关闭时触发
      this.socket.onclose = (event) => {
        console.log("WebSocket连接已关闭", event);
      };

      // 连接发生错误时触发
      this.socket.onerror = (error) => {
        console.error("WebSocket错误:", error);
      };
    },

  },
  beforeDestroy() {
    // 确保在组件销毁时关闭WebSocket连接
    if (this.socket) {
      this.socket.close();
    }
  }
}

vue3路由跳转关闭WebSocket请求

beforeUnmount() {
    console.log('关闭socket')
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  },
喜欢 (0)