数据实时刷新,如果采用普通的HTTP连接,前后端无法一直保持联系,麻烦的时候可能还需要采用轮询的机制,所以使用WebSocket连接效果还是比较好的 ,采用接口定时刷新,发现效率很低,所以考虑采用websocket实现
<template>
</template>
<script>
export default {
data() {
return {
websock: null,
}
},
created(){ //页面刚进入时开启长连接
this.initWebSocket()
},
methods: {
initWebSocket(){ //初始化weosocket
const wsuri = ' ' //ws地址
this.websock = new WebSocket(wsuri);
this.websocket.onopen = this.websocketonopen;
this.websocket.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
},
websocketonopen() {
console.log("WebSocket连接成功");
// 每30秒发一次数据,防止连接断开
let self = this;
this.timers = setInterval(() => {
try {
self.websock.send('test')
console.log('发送消息');
}catch(err){
console.log('断开了:' + err);
self.connection()
}
}, 30000)
},
websocketonerror(e) { //错误
console.log("WebSocket连接发生错误");
this.initWebSocket(); // 连接失败后尝试重新连接
},
websocketonmessage(e){ //数据接收
const redata = JSON.parse(e.data);
console.log(redata.value);
},
websocketsend(agentData){//数据发送
this.websock.send(agentData);
},
websocketclose(e){ //关闭
console.log("connection closed (" + e.code + ")");
},
},
}
</script>