// 使用 EventSource 实现服务器发送事件 (SSE) 的 Vue 示例
<template>
<div>
<h1>Vue EventSource 示例</h1>
<ul>
<li v-for="(message, index) in messages" :key="index">{{ message }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
messages: []
};
},
mounted() {
this.initEventSource();
},
methods: {
initEventSource() {
const eventSource = new EventSource('/stream'); // 连接到服务器的流地址
eventSource.onmessage = (event) => {
// 当收到消息时,将其添加到消息列表中
this.messages.push(event.data);
};
eventSource.onerror = (error) => {
console.error('EventSource failed:', error);
eventSource.close(); // 关闭连接
};
}
},
beforeDestroy() {
// 组件销毁前关闭 EventSource 连接
if (this.eventSource) {
this.eventSource.close();
}
}
};
</script>
<style scoped>
ul {
list-style-type: none;
padding: 0;
}
li {
margin: 5px 0;
}
</style>
模板部分 (<template>
):
<ul>
),用于显示从服务器接收到的消息。脚本部分 (<script>
):
data
函数返回一个包含 messages
数组的对象,用于存储接收到的消息。mounted
生命周期钩子调用 initEventSource
方法,在组件挂载后初始化 EventSource。initEventSource
方法创建一个新的 EventSource
实例,并监听 onmessage
和 onerror
事件。onmessage
事件处理程序将接收到的消息添加到 messages
数组中。onerror
事件处理程序捕获错误并关闭 EventSource 连接。beforeDestroy
生命周期钩子确保在组件销毁前关闭 EventSource 连接,防止内存泄漏。样式部分 (<style scoped>
):
上一篇:vue配置跨域
下一篇:vue3 definestore
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站