vue使用EventSource
mounted() {
if(typeof (EventSource) !== 'undefined') { //支持eventSource
var postURL = 'http……';
this.source = new EventSource(postURL);
let self = this;//因EventSource中this的指向变了,所以要提前存储一下
this.source.onopen = function() {
console.log('项目链接Eventsource成功');
};
this.source.onmessage = function(data) {
//代码块
};
this.source.onerror = function (){
console.log('项目Eventsource链接失败');
//链接失败后EventSource会每隔三秒左右重新发起链接
};
}
else {
console.log('暂不支持EventSource');
}
}
beforeDestroy(){
if(this.source){
this.source.close(); //关闭EventSource
}
}
后端怎么配置的就不知道了。
目前遇到个小问题,后台返给我一个特定的字段后,该条链接自动断掉并新建一个链接,也无报错。之前并没有遇到过此问题。