引入socket io
import io from 'socket.io-client'
实现一个socket并获取到数据
try {
const socket = io(`${SOKET_URL}/monitor`)
this.socket = socket
console.log('初始化socket', socket)
this.socket.open()
this.socket.on('real_data', ({data}) => {
console.log('data', data)
const res = JSON.parse(data)
// this.res = res
// console.log('res', JSON.stringify(res))
const { deviceNumber, deviceType } = res
// if (deviceNumber === 'M0000000001') return
// if (fd=== res.fd) {
const gfh= this.gfh
if (deviceType === 0) {
// 轿顶设备
gfh.floorNum = res.floorNum
gfh.direction =
res.direction === 0
? '停止'
: res.direction === 1
? '上行'
: '下行'
// monitorData.voltage1 = randomNumber(3.5, 4.2)
gfh.actualDistance = res.actualDistance + 'm'
gfh.leftDoor = res.leftDoor === 0 ? '开启' : '关闭'
gfh.rightDoor = res.rightDoor === 0 ? '开启' : '关闭'
gfh.actualSpeed = res.speed
gfh.carvoltageStatus =
res.voltageStatus === 0 ? '正常' : '异常'
gfh.carvoltage =
res.actualVoltage + 'V'
gfh.radarStatus = res.radarStatus === 0 ? '正常' : '异常'
gfh.trappedPeople = res.trappedPeople === 0 ? '否' : '是'
} else {
// 机房设备
// monitorData.wire = res.wire
gfh.temperature = res.actualTemp + '°C'
gfh.roomvoltageStatus =
res.voltageStatus === 0 ? '正常' : '异常'
gfh.roomvoltage =
res.actualVoltage + 'V'
// monitorData.actualTemp = res.tempStatus + '°C'
gfh.actualWire =
res.actualWire.length > 0 ? res.actualWire : '0,0,0,0'
gfh.tempStatus = res.tempStatus === 0 ? '正常' : '异常'
}
this.gfh= gfh
console.log(this.monitorData)
// }
})
} catch (e) {
console.log(e)
}
注意需要后端配合
否则可以使用ajax长轮询的方式来实现
页面销毁关闭socket
beforeDestroy () {
clearInterval(this.timer)
this.socket && this.socket.close()
//this.source && this.source.close()
},