WebSocket实例 Vue中使用websoket

我这里是一个简单的实例,不断接收服务器中的返回的数据进行一个现实

      formatDate(date) {
            if (date) {
                if (typeof date === 'object') {
                    return moment(date).format('YYYY-MM-DD HH:mm:ss');// moment.js引入
                }
            }
            return date;
        },
      sendMsgToServer(ws, needReq) {
            if (ws) {
                ws.send(needReq);
            } else {
                this.$notify({
                    type: 'error',
                    title: '操作失败!',
                    message: 'connection not established, please connect.'
                });
            }
        },
        initWs() {
            const request_type = location.protocol === 'https:' ? 'wss' : 'ws';
            const url = `${window.location.host}api_`;// api_项目中的代理(dev.conf.js)的全局替换的地址,如果服务器没有写对应的接口,会报错的哈,
            const reqKey = '2020930';// 根据需求传入参数
            const socket_url = `${request_type}://${url}/dps/sqllogwebsocket?${reqKey}`;
            const ws = new WebSocket(socket_url);
            ws.onopen = function () { // 发起请求
                this.sendMsgToServer(ws, 'true');
            };
            ws.onmessage = function (event) {
                if (event.data == 'wait') { // wait再次发送请求,连接未建立,请连接
                    this.sendMsgToServer(ws, 'false');
                } else {
                    try {
                        const logData = { date: this.formatDate(new Date()), info: event.data };
                        // if (logData) {
                        //     this.execLogsVisible = true;// 显示的内容的弹窗
                        // } else {
                        //     this.execLogsVisible = false;
                        // }
                        this.logs.push(logData);// 最终渲染到页面上的数据
                    } catch (e) {
                        console.error(e);
                    }
                }
            };
            ws.onclose = (event) => { // 关闭连接
                console.info(event);
            };
            // 测试日志模拟websoket5毫秒刷新数据----------
            /* var index = 0
                var interVal = setInterval(function() {
                	if (index > 50) {
                		clearInterval(interVal);
                	}
                	var logData = {date: self.formatDate(new Date()), info: '刷新'};
                	outputTab.logs[logLastIndex].logs.push(logData);
                	index++;
                }, 500); */
        },
        
原文地址:https://www.cnblogs.com/wangliko/p/15261787.html