如何再vue中使用 WebSocket?

websockt 最大的优势就是后端能够向前端实时推送数据,而前端只需要一个监听,就能够实现数据的相应变化
<template> <div> <button @click="freeLowControl">弹出下控页面</button> <!-- 下控弹框 --> <el-dialog title="提示" :visible.sync="dialogVisibleCtl" width="30%"> <div style="text-align:left"> <p class="lineHeight">是否确认下控 ?</p> <p class="lineHeight"> <p>日志信息:</p> <p style="color:red" v-html="record"></p> </p> </div> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisibleCtl = false" size="mini">关 闭</el-button> <el-button type="primary" @click="saveControlSing" size="mini" :loading="loading" id="contrlBtn">确 定</el-button> </span> </el-dialog> </div> </template> <script> export default { data() { return { soket: "", socktPath: "", //WebSocket地址, sendVal: "", //发送数据 dialogVisibleCtl: false }; }, methods: { //初始化webSockt initWebsocket() { this.socktPath = window.$url_front.webSocketUrl + "/socketServer/" + JSON.parse(localStorage.userMsg).id; if (typeof WebSocket === "undefined") { alert("您的浏览器不支持socket"); } else { // 实例化socket this.socket = new WebSocket(this.socktPath); //监听socket连接; this.socket.onopen = this.open; // 监听socket错误信息 this.socket.onerror = this.error; // 监听socket消息 this.socket.onmessage = this.getMessage; // 关闭连接 this.socket.onclose = this.close; } },
  //websocket连接成功的回调方法 open() { console.log("socket连接成功", this.socket);
   //每次连接成功,把上次交互所保存的信息给删除掉,将loading设为false,允许操作; this.record = "";
    this.loading = false;
    //连接成功后,向后端发送数据 this.sendData(); },
  //websocket连接失败的回调方法 error() { console.log("连接失败.");
    //设置record以及loading为true,不让用户继续操作 this.record = "ws连接失败...";
    this.loading = true;
   },
  //websocket获取数据的回调方法 getMessage(msg) { this.record = msg.data; console.log("返回数据=========", msg); }, sendData() { this.sendVal = "underControl;" + JSON.parse(localStorage.userMsg).id + ";" + String(new Date().getTime()); //前端和后端做一个约定,来确定发送数据的格式;非常关键 this.sendTime = String(new Date().getTime()); //发送数据
   // this.socket.readyState : 一般情况 0代表连接成功 1代表失败 if (this.socket.readyState == 1) { this.socket.send(this.sendVal); } }, freeLowControl() { this.dialogVisible = true;
    this.initWebSocket() }, //下控确定 saveControlSing() { //socket.readyState 是否连接成功 let contrlBtn = document.getElementById("contrlBtn"); contrlBtn.innerHTML = "请求中..."; this.loading = true; setTimeout(() => { if (this.socket.readyState == 1) { let pointArr = this.tablePoint.pointDataList; let pointList = []; pointArr.forEach(item => { let obj = {}; obj.data_id = item.data_id; obj.value = item.lowControlVal; pointList.push(obj); }); let parm = { token: this.token, points_values: JSON.stringify(pointList), wid: this.sendTime }; api_lak.underControlByFree(qs.stringify(parm)).then(res => { if (res) { this.$emit("refreshDataSet", this.tablePoint.under_id);
         //成功后 设置loading为false 允许用户的下次操作
this.loading = false;
          contrlBtn.innerHTML = "确定";
        } }); } else { this.$message({ message: "webSocket连接失败", type: "error" }); this.$emit("refreshDataSet", this.tablePoint.under_id); } }, 1000); } } }; </script>

  

原文地址:https://www.cnblogs.com/wangqi2019/p/12553394.html