VUE中使用EventSource接收服务器推送事件

// Vue项目中,EventSource触发的事件中this指向变了
// 使用const that = this,然后在EventSource触发的事件中使用that

if (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接收服务器推送事件!');
}

猜你喜欢

转载自blog.csdn.net/sleepwalker_1992/article/details/118221953