数据推送¶
数据推送和点位注册不限制技术,可以使用 Socket 也可以使用轮询。下面以 Socket 为例,可根据以下代码改成轮询方式。
核心方法¶
this.$refs.preview.getPointList() // 获取图纸所有点位信息
this.$refs.preview.changeData(data) // 将获取到的数据发送给组件
Socket 接入示例¶
<template>
<preview
:svgId="id"
:webtopoAPI="webtopoAPI"
:isConnect="isConnect"
ref="preview"
@register="register"
></preview>
</template>
<script>
import * as webtopoAPI from '@/api/webtopo/index';
import { getToken } from '@/utils/token-util';
export default {
data() {
return {
id: null,
webtopoAPI,
isConnect: false
};
},
created() {
this.id = this.$route.query.id;
this.$socket.io.uri = `${location.protocol}//${location.hostname}:8031`;
this.$socket.connect();
},
methods: {
// 点位注册,组件会将图纸用到的所有点位发送给 register 方法
register(pointList) {
this.$socket.emit('register', {
code: getToken(),
points: pointList
});
}
},
sockets: {
// 重连时重新注册点位信息
connect: function () {
this.isConnect = true;
this.$socket.emit('register', {
code: getToken(),
points: this.$refs.preview.getPointList()
});
},
// 断开连接时通知组件,组件会提示用户后台断开连接
disconnect: function () {
this.isConnect = false;
console.log('断开连接');
},
// 出错时提示用户
autoError: function (msg) {
this.$message.error(msg);
},
// 重连时重新注册点位信息
reconnect: function () {
this.isConnect = true;
this.$socket.emit('register', {
code: getToken(),
points: this.$refs.preview.getPointList()
});
console.log('重新连接');
},
// 数据接收函数,接收到数据变化发送给组件
data(data) {
this.$refs.preview.changeData(data);
}
},
// 关闭页面时断开连接
beforeDestroy() {
this.sockets.disconnect();
}
};
</script>
轮询方式¶
若使用轮询,只需定时调用后台接口获取数据,然后通过 this.$refs.preview.changeData(data) 将数据推送给组件即可,无需 Socket 相关代码。