基于 SSE 协议实现任务进度条的实时显示——Vue2 + Spring Boot 实践
// Vue 2 组件代码片段
<template>
<div>
<div class="progress">
<div class="progress-bar"
role="progressbar"
:style="{ width: progress + '%' }"
:aria-valuenow="progress"
aria-valuemin="0"
aria-valuemax="100">
{{ progress }}%
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
progress: 0,
eventSource: null
};
},
created() {
this.connectToEventStream();
},
methods: {
connectToEventStream() {
this.eventSource = new EventSource('/task/progress');
this.eventSource.addEventListener('progress', (event) => {
this.progress = parseInt(event.data);
});
this.eventSource.addEventListener('error', (event) => {
console.log('EventSource error:', event);
});
}
},
beforeDestroy() {
if (this.eventSource) {
this.eventSource.close();
}
}
};
</script>
这个代码示例展示了如何在Vue 2应用中使用EventSource与Spring Boot后端通讯,实现了一个简单的进度条的实时更新。在created钩子中,它创建了一个EventSource实例,监听来自后端的'progress'事件,并更新组件的progress数据属性。在beforeDestroy钩子中,确保关闭了EventSource,以防止内存泄漏。
评论已关闭