<script setup>
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { ref } from 'vue';

const message = ref('');
const result = ref('');

/**
 * Establishes a server-sent event stream to receive real-time messages from the server.
 *
 * @param {object} [params={}] - The parameters to be sent to the server.
 *
 * @returns {void}
 */
const getRealtimeMessage = ()=>{
  const params = {
    message: message.value
  }; 
  const ctrlAbout = new AbortController();
  fetchEventSource('/api/events', {
    method: 'POST',
    headers: {
      'Authorization': 'token',
      'Content-Type': 'application/json', // 文本返回格式
    },
    body: JSON.stringify(params),
    signal: ctrlAbout.signal,
    openWhenHidden: true, // 在浏览器标签页隐藏时保持与服务器的EventSource连接
    onmessage(res) {
      // 操作流式数据
      result.value += res.data + '\n';
    },
    onclose(res) {
      // 关闭流
    },
    onerror(error) {
      // 返回流报错
    }
  })
}
</script>

<template>
    <div>
        <van-field v-model="message" placeholder="请输入" type="textarea" />
        <van-button type="primary" @click="getRealtimeMessage">发送</van-button>
        <van-field v-model="result" type="textarea" />
    </div>
</template>

<style scoped>

</style>