当数据需要实时更新时,一种方法是通过定时器轮询,但这种方法比较耗费性能,另一种方法是通过websocket建立连接,实时推送数据。如下:

mounted:function(){

this.initWebSocket();

},

destroyed: function() {

//页面销毁时关闭

this.websocket.onclose = this.websocketclose();

},

methods:{

initWebSocket(){ //初始化

this.websocket = new WebSocket('');

var that = this.websocket;

that.onopen = this.websocketonopen;

that.onerror = this.websocketonerror;

that.onmessage = this.websocketonmessage;

that.onclose = this.websocketclose;

},

websocketonopen() { //发送消息

this.websocket.send('');

console.log("WebSocket连接成功");

},

websocketonerror(e) { //连接错误

console.log("WebSocket连接发生错误");

// 此时需要重连

setTimeout(() => {

this.initWebSocket();

}, 2000);

},

websocketonmessage(e){ //数据接收

//处理逻辑

},

websocketclose(e){ //连接关闭

console.log("connection closed (" + e.code + ")");

},

}

如此,貌似websocket也不难啦!

好文链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: