本文主要是介绍VUE中使用EventSource接收服务器推送事件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
// Vue项目中,EventSource触发的事件中this指向变了
// 使用const that = this,然后在EventSource触发的事件中使用thatif (typeof (EventSource) !== 'undefined') {const evtSource = new EventSource('/log/print', { withCredentials: true }) // 后端接口,要配置允许跨域属性// 与事件源的连接刚打开时触发evtSource.onopen = function(e){console.log(e);}// 当从事件源接收到数据时触发evtSource.onmessage = function(e){console.log(e);}// 与事件源的连接无法打开时触发evtSource.onerror = function(e){console.log(e);evtSource.close(); // 关闭连接}// 也可以侦听命名事件,即自定义的事件evtSource.addEventListener('notice', function(e) {console.log(e.data)})
} else {console.log('当前浏览器不支持使用EventSource接收服务器推送事件!');
}
这篇关于VUE中使用EventSource接收服务器推送事件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!