前后端分离的项目,vue可以使用EventSource监听后台数据变化
1.先判断浏览器是否支持EventSource
2.定义EventSource对象的变量,onopen是连接的时候触发、onmessage是接收消息的时候触发、onerror是连接失败时候触发,EventSource是连接失败后会重新发起连接的。
重点是{ withCredentials: true }, 因为前后端分离会产生跨域问题
完整代码(写在mounted):
const that = this
if (typeof (EventSource) !== 'undefined') {
var audio = new Audio()
audio.src = require('@/assets/test.wav') // 声音文件
const sourc = new EventSource('/sendMessage', { withCredentials: true }) // 后端接口,要配置允许跨域属性
sourc.onopen=function(e){}
sourc.onmessage=function(e){
audio .play()
that.$notify({
title: '打印结果',
message: e.data,
type: 'success'
})
if (!userInfo) { // 退出登录
sourc.close()
}
}
sourc.onerror=function(e){}
} else {
that.$message.error('当前浏览器不支持服务器发送的事件')
}
EventSource从父接口 EventTarget 中继承了属性和方法,其内置了 3 个EventHandler 属性、2 个只读属性和 1 个方法:
EventHandler 属性
EventSource.onopen 在连接打开时被调用。
EventSource.onmessage 在收到一个没有 event 属性的消息时被调用。
EventSource.onerror 在连接异常时被调用。
只读属性
EventSource.readyState 一个 unsigned short 值,代表连接状态。可能值是 CONNECTING (0), OPEN (1), 或者 CLOSED (2)。
EventSource.url 连接的 URL。
方法
EventSource.close() 关闭连接