项目中需要实时更新数据,马上就想到了websocket,以下是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连接发生错误");
},
websocketonmessage(e){ //数据接收
//处理逻辑
},
websocketclose(e){ //关闭
console.log("connection closed (" + e.code + ")");
},
}