initWebSocket() { //初始化websocket this.ws = new WebSocket(url) // 在data中定义ws为null this.ws.onmessage = this.websocketonmessage this.ws.onopen = this.websocketonopen this.ws.onerror = this.websocketonerror this.ws.onclose = this.websocketclose }, websocketonopen() { // 连接websocket成功时的回调 console.log('连接成功') }, websocketonmessage(e) { //获取websocket推送的数据 let re_msg = e.data // 转码,防止有百分号出现 re_msg = unescape(re_msg.replace(/\u/g, '%u')) re_msg = JSON.parse(re_msg) }, // 连接失败时重新连接 websocketonerror() { this.initWebSocket() }, // 断开链接后报错 websocketclose(e) { this.initWebSocket() },注意:如果需要发送心跳的话,只需要在onopen里写一个定时器,定时发送心跳数据即可,离开页面时记得清除定时器。例: setInterval(() => { if (_this.ws != null && _this.ws.readyState == _this.ws.OPEN) { let req = { 自定义字段: '自定义数据', } _this.ws.send(JSON.stringify(req)) } }, 7500)