当对服务器发送的事件使用@microsoft/fetch-event-source 时,Vue data() 在事件中不可用

Vue data() is unavailable in events when using @microsoft/fetch-event-source for Server Sent Events

我正在尝试使用 fetchEventSource(来自 @microsoft/fetch-event-source)来处理服务器发送的事件以将数据流式传输到客户端。它有效,因为数据已返回并且我可以将其记录到控制台,但是当我尝试在 onmessage 事件中更新我的 vue 数据时,出现错误:

TypeError: Cannot set properties of undefined (setting 'messages')

关于实现此功能的最佳方法有什么想法吗?

基本测试模板:

<template>
  <div>
    <p>
      <label>Message</label><br />
      <textarea id="messages" v-model="messages"></textarea><br />
      <button @click="getMessage">GET</button>
    </p>
  </div>
</template>

和脚本:

import { fetchEventSource } from "@microsoft/fetch-event-source";

export default {
  data() {
    return {
      messages: "",
    };
  },
  mounted() {
    this.messages = "initialized"; // this works
  },
  methods: {
    getMessage() {
      fetchEventSource("url-here", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        onmessage(msg) {
          console.log("message", msg.data); // this works - data is here!
          this.messages = msg.data; // this returns the error
        },
      });
    },
  },
};

你可以试试箭头函数之类的:

getMessage() {
  const self = this
  fetchEventSource("url-here", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    onmessage(msg) {
      console.log("message", msg.data); // this works - data is here!
      self.messages = msg.data; // this returns the error
    },
  });
},