Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue eventsource

作者:▄对对碰   发布日期:2025-04-21   浏览:107

// 使用 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>

解释说明:

  1. 模板部分 (<template>):

    • 包含一个标题和一个无序列表 (<ul>),用于显示从服务器接收到的消息。
  2. 脚本部分 (<script>):

    • data 函数返回一个包含 messages 数组的对象,用于存储接收到的消息。
    • mounted 生命周期钩子调用 initEventSource 方法,在组件挂载后初始化 EventSource。
    • initEventSource 方法创建一个新的 EventSource 实例,并监听 onmessageonerror 事件。
      • onmessage 事件处理程序将接收到的消息添加到 messages 数组中。
      • onerror 事件处理程序捕获错误并关闭 EventSource 连接。
    • beforeDestroy 生命周期钩子确保在组件销毁前关闭 EventSource 连接,防止内存泄漏。
  3. 样式部分 (<style scoped>):

    • 定义了一些简单的样式,使消息列表看起来更整洁。

上一篇:vue配置跨域

下一篇:vue3 definestore

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站